简体   繁体   中英

Floating point precision variation in Python 2.7.5

If I run the following code in Python 2.7.5 console:

>>> 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.)

This is the difference between repr and str :

>>> 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 ).

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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