python 中的round()函数并不是严格意义上的四捨五入

四舍(捨)五入(定义):是数值修约的一种规则,其中数值修约规则常用的共三种,还包含五捨六入和四捨六入五留双规则。
开始学python时,我们总会遇到一个问题,就是如何进行四捨五入,很多人第一个联想到的函数就是BIF(build-in-functions)中的round(),然而round()函数可以是数学上的四捨五入吗?答案是否定的。
代码如下:

class Debug:
    def __init__(self):
        self.x0 = 0.4
        self.x1 = 0.5
        self.x2 = 0.6
        self.x3 = 1.1
        self.x4 = 1.5
        self.x5 = 1.9
        self.x6 = 2.5
        self.x7 = 2.6
    
    def mainProgram(self):
        self.x0 = round(self.x0)
        self.x1 = round(self.x1)
        self.x2 = round(self.x2)
        self.x3 = round(self.x3)
        self.x4 = round(self.x4)
        self.x5 = round(self.x5)
        self.x6 = round(self.x6)
        self.x7 = round(self.x7)
        
        print(self.x0)              # 0 
        print(self.x1)              # 0
        print(self.x2)              # 1
        print(self.x3)              # 1
        print(self.x4)              # 2
        print(self.x5)              # 2
        print(self.x6)              # 2
        print(self.x7)              # 3
        
        
main = Debug()
main.mainProgram()

我们可以看到,当变量的值为0.4时,使用round()函数后的结果为0。当变量值为0.6时,使用了round()函数后的值为1。当变量的值为1.51.9时,使用了round()函数后的值为2。当变量的值为2.6时,使用了round()函数后的值为3。看起来好像是四舍五入了。但是当变量的值为0.5时,使用了round()函数后的值为0。当变量的值为2.5时,使用了round()函数后的值还是2,而当变量值为由此我们可以断定round()函数并不是真正意义上的四舍五入。
实际上,round()是会将数字保留有效个位数并趋向于最近的偶数,这也是为什么1.5和2.5的值均为2的原因了。因此round()函数实际上表现的是四捨六入五留双规则。

那么有没有办法让round()实现真正意义上的四捨五入呢?答案是肯定的。(待更新。。。)

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/108433486
今日推荐