|
Original |
Translation |
|
10
|
|
|
|
11
|
Why are floating point calculations so inaccurate?
|
|
|
12
|
People are often very surprised by results like this::
|
|
|
13
|
>>> 1.2 - 1.0 0.199999999999999996
|
|
|
14
|
|
15
|
The internal representation of floating point numbers uses a fixed number of binary digits to represent a decimal number. Some decimal numbers can't be represented exactly in binary, resulting in small roundoff errors.
|
|
|
16
|
In decimal math, there are many numbers that can't be represented with a fixed number of decimal digits, e.g. 1/3 = 0.3333333333.......
|
|
|
17
|
In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. .2 equals 2/10 equals 1/5, resulting in the binary fractional number 0.001100110011001...
|
|
|
18
|
Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2.
|
|
|
19
|
A floating point number's ``repr()`` function prints as many digits are necessary to make ``eval(repr(f)) == f`` true for any float f. The ``str()`` function prints fewer digits and this often results in the more sensible number that was probably intended::
|
|