Search code examples
pythonfloating-pointlimitnumericsignificant-digits

Where are these tailing digits in Python value from?


In mathematics, the value 1/3 is 0.333(3 to infinity).

However, Python prints out wrong digits at the tail.

print(f"{1/3:.100f}".rstrip("0"));
print(f"{1/3:.100f}");

Result:

0.333333333333333314829616256247390992939472198486328125

Result (no rstrip):

0.3333333333333333148296162562473909929394721984863281250000000000000000000000000000000000000000000000

Where are those tailing digits (which are not 3) from?


Solution

  • From the docs

    Floating-point numbers are represented in computer hardware as base 2 (binary) fractions

    For decimal fractions which cannot be represented as binary fractions (e.g. repeating decimals) they are approximated by a binary fraction up to the precision limit:

    Stop at any finite number of bits, and you get an approximation. On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits [...]

    Hence, 1/3. is not stored as 0.333.... (repeating) but as an approximation (ostensibly a 53-bit binary fraction).