简体   繁体   English

Python 2.7.5中的浮点精度变化

[英]Floating point precision variation in Python 2.7.5

If I run the following code in Python 2.7.5 console: 如果我在Python 2.7.5控制台中运行以下代码:

>>> import math
>>> math.radians(0.000001)

I get 我明白了

1.7453292519943295e-08

However, if I put the same code in a file: 但是,如果我将相同的代码放在一个文件中:

$ cat floatingtest.py
import math
print(math.radians(0.000001))

And run it, I get: 并运行它,我得到:

$ python.exe floatingtest.py
1.74532925199e-08

Why the difference in floating point precision when running code in a script vs. running code in the console? 为什么在脚本中运行代码与在控制台中运行代码时浮点精度的差异?

(Python 3.3 doesn't seem to have this 'issue'. Both ways return the same high-precision value.) (Python 3.3似乎没有这个“问题”。两种方式都返回相同的高精度值。)

This is the difference between repr and str : 这是reprstr之间的区别:

>>> repr(math.radians(0.000001))
'1.7453292519943295e-08'
>>> str(math.radians(0.000001))
'1.74532925199e-08'

By default, print calls str on its arguments, but the REPL displays objects using repr when there is no assignment (and the return value is not None ). 默认情况下, print对其参数调用str ,但是当没有赋值时,REPL使用repr显示对象(并且返回值不是None )。

It has no relation to precision only to the representation: 它与精度仅与表示无关:

In [1]: import math    
In [2]: math.radians(0.000001)
Out[2]: 1.7453292519943295e-08    
In [3]: print math.radians(0.000001)
1.74532925199e-08    
In [4]: str(math.radians(0.000001))
Out[4]: '1.74532925199e-08'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM