awitney
awitney

Reputation: 21

Precision difference between python2 and python3

i am trying to understand a difference between python2 and python3:

$ python2
Python 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
>>> print(2.2*55)
121.0

$ python3
Python 3.4.5 (default, May 29 2017, 15:17:55)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
>>> print(2.2*55)
121.00000000000001

I guess this is to do with precision, but how do I make python3 give me 121.0

Thanks

Upvotes: 1

Views: 685

Answers (1)

W.Mann
W.Mann

Reputation: 923

This has nothing to do with precision of the arithmetics, it's only about output formatting:

% python 
Python 2.7.9 (default, Jun 29 2016, 13:08:31) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print(2.2*55)
121.0
>>> print("%.20f" % (2.2*55))
121.00000000000001421085

% python3
Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(2.2*55)
121.00000000000001
>>> print("%.20f" % (2.2*55))
121.00000000000001421085

the culprit is that 2.2 is not representable as a float. It is rounded to something close:

>>> print("%.20f" % (2.2))
2.20000000000000017764

If you don't want to see that many zeros followed by digit in the output, limit the output precision. If you want to have more decimal friendly arithmetic, you can use the Decimal type.

See also this question: Python format default rounding when formatting float number

Upvotes: 1

Related Questions