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

Posted

技术标签:

【中文标题】如何在python大数计算中抑制科学计数法【英文标题】:How to suppress scientific notation in python large number calculation 【发布时间】:2020-10-15 13:11:46 【问题描述】:

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

【问题讨论】:

检查声明14*15**13 == dst[-1]。您正在检查14*15**13是否等于14,如果您想以非科学形式打印值,请参阅here。科学计数法不会降低计算的准确性,而是用于节省空间。 1e-5==0.00001 将返回 true。 抱歉打错了,我检查了14*15**13 ==[float(dst[i])*float(rst)**float(i) for i in range(len(dst))][-1]False 【参考方案1】:
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。

【讨论】:

谢谢朋友。我在我的程序中的最终目的是获得该列表的总和,并且在上下文中我错误地分配了一个变量。使用int() 更改dtype 使程序正常运行。你是对的,谢谢朋友。【参考方案2】:

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

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

【讨论】:

我明白了。但是在计算过程中,使用 float 和 int 会得到完全不同的结果,我很有信心这不是打印问题,因为当涉及到大量计算时,float 结果和 int 结果之间的== 比较总是False (+ - * **)

以上是关于如何在python大数计算中抑制科学计数法的主要内容,如果未能解决你的问题,请参考以下文章

R语言ggplot2可视化包抑制数据轴使用科学计数法实战

为啥 python 在数据框中计算时返回科学计数法?

PL/SQL中查询Oracle大数(17位以上)时显示科学计数法的解决方法

R语言ggplot2可视化格式化坐标轴的数值:抑制科学计数法suppress Scientific Notation

R语言ggplot2可视化格式化坐标轴的数值:抑制科学计数法suppress Scientific Notation

dataframe.describe() 抑制科学记数法[重复]