Python3 Strange Float Rounding
Can someone explain me why i do not get 166.9 (i know there is a round() function) i just would like to understand. :) >>> 165.0 + 1.45 + 0.45 166.89999999999998
Solution 1:
This is because in computer are numbers represented in binary form. This is not issue only in Python, but computers generally.
Solution 2:
Floating point numbers are stored in 64 bits in python. 1 bit is the sign, 52 bits for the mantissa, and 11 for the exponent. To get the decimal value from these 3 components the computer will do sign * mantissa * 2 ^ exponent.
Not all numbers can be stored perfectly in this form. Only 52 bits to store the number. For example, 11.3 can not be stored perfectly in this form, you can see the exact value of a number with this.
from decimal import Decimal
print(Decimal(11.3))
When you added 165.0 + 1.45 + 0.45.
>>>print(Decimal(165))
165
>>>print(Decimal(1.45))
1.4499999999999999555910790149937383830547332763671875
>>>print(Decimal(0.45))
0.450000000000000011102230246251565404236316680908203125
You were not actually adding those exact values.
For more information concerning the floating point number system visit Wikipedia.
Post a Comment for "Python3 Strange Float Rounding"