为什么舍入0.5(十进制)不精确?

时间:2016-06-29 12:45:41

标签: python floating-point rounding floating-accuracy

一半,即十进制的0.5,具有精确的二进制表示:0.1

然而,如果我将它四舍五入为整数,我得到0而不是1.我尝试使用Python和C,它的行为相同。例如。 python代码:

>>> a,b,c = 0.49, 0.5, 0.51
>>> [round(x) for x in (a,b,c)]
[0, 0, 1]
>>> "%.0f %.0f %.0f" % (a,b,c)
'0 0 1'

有趣的是,

>>> a,b,c = 0.049, 0.05, 0.051
>>> [round(x,1) for x in (a,b,c)]
[0.0, 0.1, 0.1]
>>> "%.1f %.1f %.1f" % (a,b,c)
'0.0 0.1 0.1'

我知道许多类似的问题,例如Python rounding error with float numbersPython tutorial on floating point arithmetics和强制性What Every Computer Scientist Should Know About Floating-Point Arithmetic

如果数字具有精确的二进制表示,例如(十进制)0.5,是否应该正确舍入?

编辑:问题发生在版本3.4.3中,但不发生在版本2.7.6

1 个答案:

答案 0 :(得分:9)

我知道他们改变了python 3中的round方法。

所以,在v2.7.3下:

import {Component,Injectable} from 'angular2/core';
import {sharedService} from 'src/sharedService';
import {someService} from 'src/someService';
import 'rxjs/Rx';
@Component({
  selector: 'thecontent',
    template: `
    <h1>Reserved parking</h1>
    {{myjson|json}}
    `
})
export class reservedParking{
  myjson:string[];
  constructor(private ss: sharedService) {
    ss.parkingType$.subscribe((res)=>this.myjson=res); 
  }
}

在v3.2.3下:

In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0

我不知道它是否对你有所帮助,但由于我的声誉很低,因此我无法发表评论。

此问题的回答更为恰当:Python 3.x rounding behavior