0

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?

Dee
  • 7,455
  • 6
  • 36
  • 70
  • Could this be an error this `rstrip` function you are using? If not, it could be something similar to what BigDecimal fixes in Java. – Aaron Mann Jan 16 '20 at 02:19
  • without rstrip, the digits at tail are still random – Dee Jan 16 '20 at 02:26
  • no, im asking about the value in python – Dee Jan 16 '20 at 02:30
  • 2
    Floating point inaccuracies exist no matter what language it is. I think the marked duplicate goes into more depth about why these inaccuracies exist. – iz_ Jan 16 '20 at 02:38

2 Answers2

2

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).

William Miller
  • 9,839
  • 3
  • 25
  • 46
1

As you add more precise values, python calculates a number closer to the actual value. Think about it this way, using 1/3:

0.3

or

0.33

or

0.333

"No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3."

Aaron Mann
  • 84
  • 9