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

时间:2020-10-15 13:11:46

标签: python scientific-notation largenumber

在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大数计算中抑制科学计数法

2 个答案:

答案 0 :(得分:0)

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。如果仅使用int(而不划分),则会得到int,在这种情况下将不使用e表示法。

答案 1 :(得分:0)

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

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