-3

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
hanoo
  • 4,175
  • 2
  • 26
  • 19

2 Answers2

0

This is because in computer are numbers represented in binary form. This is not issue only in Python, but computers generally.

von Oak
  • 823
  • 5
  • 14
  • My 2€ calc can handle this calcul... and this simpe c program find the correct answer: #include int main() { printf("%f\n", 165.0 + 1.45 + 0.45); return 0; } – hanoo Aug 04 '16 at 09:47
  • Yes, naturally. Look to links about this topic. Briefly your calculator has the numbers internally also in binary form and have the numbers like 1.45 internally represented e.g. as 1.4499999999999999999. But he hasn't so many places to show you his internal number, that he round it and show you on the display 1.45. But computer has much more space in memory, he hasn't to round it for you, so he has bigger accuracy in binary form and doesn't round it, if it's not necessary. Paradoxically, the cheaper device round it and it seems more accurate for us, but internally it's not. – von Oak Aug 04 '16 at 09:57
  • Your example is nice, but you have to know, what formatting `"%f\n"` means. Try for example this formatting `"%.30f\n"`. It will have thirty decimal points. Result is: 166.899999999999977262632455676794. Whole program: `#include int main() { printf("%.30f\n", 165.0 + 1.45 + 0.45); return 0; }` – von Oak Aug 04 '16 at 10:12
0

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.