Python舍入错误

bat*_*n47 3 python python-2.7

我只是使用python作为计算,我看到了这一点

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 62 * 41.2 * 2 / 250
20.435200000000002
>>> 62 * 4.12 * 2 / 25
20.4352
>>>
Run Code Online (Sandbox Code Playgroud)

只是为了确保我通过gcc解雇了以下代码,但这并未向我显示上述行为.我知道这可能是四舍五入的事情,但应该是统一的.为什么python在数学上加起来跟踪00000000002它不应该在那里.

C/C++代码

#include <stdio.h>
int main () {
  printf ("%lf %lf \n", 62 * 41.2 * 2 / 250, 62 * 4.12 * 2 / 25);
}
Run Code Online (Sandbox Code Playgroud)

结果是

20.435200 20.435200

如果有人对特定数字感到好奇,他们属于一些引擎位移计算比较:)

Tha*_*vas 8

除了@Ashwini Chaudhary的回答,

题 :

为什么python在数学上加起来跟踪00000000002它不应该在那里

答案:

因为机器中的价值并不准确.这不是Python中的错误或代码中的错误.您将在支持二进制浮点运算的所有语言中看到完全相同的问题.但是,不同的语言可能会以不同的方式显示(四舍五入).

试试这个:

0.1 + 0.2
Run Code Online (Sandbox Code Playgroud)

你会得到

0.30000000000000004
Run Code Online (Sandbox Code Playgroud)

这是因为0.1无法准确地以二进制形式表示.在基数2或二进制中,0.1是无穷大重复数

0.0001100110011001100110011001100110011001100110011...
Run Code Online (Sandbox Code Playgroud)

因此,Python决定改为关闭它.

我建议你在这里阅读更多内容.