Python 值中的这些尾部数字来自哪里?

Where are these tailing digits in Python value from?

在数学中,1/3的值是0.333(3到无穷大)。

然而,Python 在尾部打印出错误的数字。

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

结果:

0.3333333333333333314829616256247390992939472198486328125

结果(无 rstrip):

0.333333333333333331482961625624739099293947219848632812500000000000000000000000000000000000000000000000

那些尾部数字(不是 3)来自哪里?

来自docs

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

对于不能表示为二进制小数的小数(例如重复小数),它们被近似为精度限制的二进制小数:

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 [...]

因此,1/3. 不是存储为 0.333....(重复),而是存储为近似值(表面上是 53 位二进制小数)。

随着您添加更精确的值,python 会计算出一个更接近实际值的数字。这样想,用1/3:

0.3

0.33

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