我想知道我的方程结果(类似于 x / y
这样的简单方程)是向上还是向下舍入。原因是在舍入后,我有两个简单的语句如下:
if h % 2 != 0: h = h + 1
if h % 4 != 0: h = h + 2
根据四舍五入的方向,我将选择
+
或-
运算符,因此如果结果四舍五入并且h % 2 != 0
,则h = h + 1
,如果结果向下舍入,则h = h - 1
。
round()
函数提供了这种信息吗?此外,我的数学计算正确吗?(我希望结果可被4整除)
如果小数点后的数字:
但是您可以使用 math 包中的 ceil
或 floor
,它们分别总是向上或向下舍入。
import math
>>> math.ceil(5.2)
6
>>> math.floor(5.9)
5
Try this to round to 4 directly :
import math
h = 53.75
rounded = math.round(h / 4) * 4
if (rounded > h):
print("Rounded up by " + str(rounded - h))
else:
print("Rounded down by " + str(h - rounded))
math.floor()
总是向下取整。 - Barmar23 / 5.0 => 4.6
,然后 math.round(4.6) => 5
最后 5 * 5 => 25
。 - dsprif h % 4 != 0: h = D(h / 4).quantize(D('1'), rounding=decimal.ROUND_HALF_UP) * 4
感谢你的提示。 - Derp3.9
和 4.4
是否被四舍五入了。你可以像这样操作:def is_rounded_down(val, ndigits=None):
return round(val, ndigits) < val
然后你可以简单地调用该函数来找出答案。
>>> is_rounded_down(3.9)
False
>>> is_rounded_down(4.4)
True
默认情况下,round()
不提供该信息,因此您需要自行检查。
对于 Python 2.X,整数除法返回一个整数并总是向下取整。
add@LM1756:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
>>> print 8/3
2
>>> print type(5/2)
<type 'int'>
add@LM1756:~$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
>>> print(8/3)
2.6666666666666665
>>> type(8/3)
<class 'float'>
>>>
round()
不会报告那个信息。但是你可以比较未舍入的结果和舍入后的结果来看哪个更大,这样就能知道了。 - John Gordon