caesar2334 发表于 2021-3-22 15:49:39

关于round() 奇进偶舍的问题,求各位大佬帮助....

是这样的,在学习round()的时候,看到帖子说round()的机制是采用了”四舍六入五看齐“的做法。当尾数为5 的时候,又采用是奇进偶舍的方法。但是当我输入round(1.15,1) 和round(1.25,1)的时候,发现一个是1.1, 一个是 1.2 .....太奇怪了..... 不是应该round(1.15,1 )输出的是1.2 的嘛
>>> round(1.15,1)
1.1
>>> round(1.25,1)
1.2

caesar2334 发表于 2021-3-22 15:57:23

我发现,在保留小数的时候,只要将1 判断为奇数,就会出现这种情况,其他的3、5、7、9都会进位。但是当1在整数位上的时候,那么就可以视作奇数正常奇进偶舍了。

jackz007 发表于 2021-3-22 16:27:13

本帖最后由 jackz007 于 2021-3-22 17:07 编辑

       看看 Python 3.8.7 的手册上说了些什么
Note:
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
       百度翻译的译文为
注:
round() 的行为可能令人惊讶:例如,round(2.675,2)给出的是2.67,而不是预期的2.68。这不是一个bug:这是因为大多数小数不能精确地表示。有关详细信息,请参阅浮点运算:问题和限制。
       毫无疑问,楼主所遭遇的正是手册上所说的所谓 "令人惊讶" 的结果。

txxcat 发表于 2021-3-22 17:56:43

参见:https://docs.python.org/zh-cn/3/tutorial/floatingpoint.html#tut-fp-issues

Daniel_Zhang 发表于 2021-3-22 20:28:55

很神奇

感觉是和精度有关

3.55 应该是会被认为是 3.5499999999999999999999999 所以 3.55 会被 ”四舍“

3.551 > 3.55 也就是 > 3.5499999999999999999999999,所以会被 ”五入“

笨鸟学飞 发表于 2021-3-23 09:30:21

浮点数的四舍五入是这样的了
你实在要四舍五入也简单啊
def rounded(a, b):
    '''参数一:浮点数
       参数二:小数点后保留位数'''
    num = '0.' + b*'0' + '5'
    temp = str(a + float(num))
    index = temp.find('.')
    temp = temp[:index+b+1]
    return float(temp)

print(rounded(1.15, 1))
print(rounded(1.25, 1))

caesar2334 发表于 2021-3-23 11:26:05

谢谢大家的解答!由于大家的回答都很好,我就设定第一个为最佳答案啦!
页: [1]
查看完整版本: 关于round() 奇进偶舍的问题,求各位大佬帮助....