有没有办法知道 python 中的某些内容是向上舍入还是向下舍入?
Is there a way to know whether something was rounded up or down in python?
我基本上想知道我的方程式(像这样 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 整除)
假设您想知道 3.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()
不提供该信息,因此您需要自行检查。
如果给定小数点后的数字是:
,则使用 round()
- >=5 即+1 将被添加到最终值。
- <5 最终值将 return 与提到的小数相同。
但是您可以使用数学包中的 ceil
或 floor
,它们总是分别向上或向下舍入。
import math
>>> math.ceil(5.2)
6
>>> math.floor(5.9)
5
试试这个直接四舍五入:
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))
对于Python2.X整数除法returns一个整数并且总是向下舍入。
add@LM1756:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
>>> print 8/3
2
>>> print type(5/2)
<type 'int'>
对于Python3.X整数除法returns一个浮点数,所以没有四舍五入。
add@LM1756:~$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
>>> print(8/3)
2.6666666666666665
>>> type(8/3)
<class 'float'>
>>>
我基本上想知道我的方程式(像这样 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 整除)
假设您想知道 3.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()
不提供该信息,因此您需要自行检查。
如果给定小数点后的数字是:
,则使用 round()- >=5 即+1 将被添加到最终值。
- <5 最终值将 return 与提到的小数相同。
但是您可以使用数学包中的 ceil
或 floor
,它们总是分别向上或向下舍入。
import math
>>> math.ceil(5.2)
6
>>> math.floor(5.9)
5
试试这个直接四舍五入:
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))
对于Python2.X整数除法returns一个整数并且总是向下舍入。
add@LM1756:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
>>> print 8/3
2
>>> print type(5/2)
<type 'int'>
对于Python3.X整数除法returns一个浮点数,所以没有四舍五入。
add@LM1756:~$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
>>> print(8/3)
2.6666666666666665
>>> type(8/3)
<class 'float'>
>>>