给定一个有理数,我需要得到最接近的整数,精确的一半向上取整(即,向正无穷大方向)。结果必须精确,这排除了float
和Decimal
,两者的精度都有限
以下代码在所有情况下都能正常工作,负数除外:
def roundhalfup(x: Fraction) -> int:
"Returns the closest integer to x, with exact ties rounded up"
#assert not x < 0, ValueError("Negative numbers not implemented")
return int(x + Fraction(1, 2))
def divroundhalfup(a: int | Fraction, b: int | Fraction) -> int:
return roundhalfup(Fraction(a, b))
例如,它在以下方面成功:
但它失败了
我知道用Decimal
和^{decimal.getcontext().prec=99999
一起使用Decimal
可能会使这个问题变得很棘手,但是如果可能的话,我想避免这种丑陋的黑客攻击。如何在没有任何舍入的情况下做到这一点?完全是整体的
在
roundhalfup
中,将int(...)
替换为math.floor(...)
:这里有一个使用} 执行的是“向偶数取整”而不是“向上取整”,但它有点花哨:
round
的解决方案。 虽然由于^{输出:
相关问题 更多 >
编程相关推荐