python大数计算中如何抑制科学计数法

How to suppress scientific notation in python large number calculation

在python中,当计算一个大数(整数或浮点数)时,似乎该数将以科学计数法存储,因此变得不准确。 例如

>>> rst = 15
>>> dst = [10, 14, 10, 14, 10, 14, 10, 14, 10, 14, 10, 14, 10, 14]
>>> [float(dst[i])*float(rst)**float(i) for i in range(len(dst))]

[10.0, 210.0, 2250.0, 47250.0, 506250.0, 10631250.0, 113906250.0, 2392031250.0, 25628906250.0, 538207031250.0, 5766503906250.0, 121096582031250.0, 1297463378906250.0, 2.724673095703125e+16]
>>> # please note the last element is stored in scientific notation
>>> # but if calculate 14*15**13 (same as how the last element is calculated)
>>> 14*15**13
>>> 27246730957031250
>>> # result is fine
>>> 14*15**13 == dst[-1]
>>> False

在python大数计算

中如何抑制科学记数法
please note the last element is stored in scientific notation
but if calculate 14*15**13 (same as how the last element is calculated)

最后一个元素是 float,而 14**15**13 的结果是 int。如果您只使用 ints(并且不除法),您将得到 int,在这种情况下不使用 e-notation。

请注意数字在内存中的存储方式和在计算中的使用方式(作为浮点数或整数)与将数字转换为字符串并在屏幕上显示的方式(四舍五入为整数、定点数或科学数)之间的区别符号)。这是两个完全独立的概念,所以看到以某种方式显示的内容并不会自动说明准确性。

In [8]: i = 123

In [9]: print('integer displayed as int: %i, as fixed point: %.1f or %.3f, and in scientific notation: %e' % (i, i, i, i))
integer displayed as int: 123, as fixed point: 123.0 or 123.000, and in scientific notation: 1.230000e+02

In [10]: f = 1.23

In [11]: print('floating point displayed as int: %i, as fixed point: %.1f or %.3f, and in scientific notation: %e' % (f, f, f, f))
floating point displayed as int: 1, as fixed point: 1.2 or 1.230, and in scientific notation: 1.230000e+00