【问题标题】:Numerical result out of range in PythonPython中的数值结果超出范围
【发布时间】:2015-07-01 07:05:52
【问题描述】:

我是 Python 的初学者。我写了一个函数来计算 10^-15 的数字。

生成代码输出时,出现错误提示“数值结果超出范围”。发生此错误的可能原因是什么?

这是我的代码。

import numpy as np
import matplotlib.pyplot as plt
T=4.32*10**19
i=input("Number of iterations ")
h=T/i
a=[0.01]*6000
t=[0.0]*6000
data = np.loadtxt('/home/user/t.txt')
t=data[:]
def f (a):
    if a!=0:    
        c=((0.75/a + 0.044/(a**2) + 0.74*(a**2))**0.5)  
        return c
    else :
        return 0

for n in range(0,5998):
    k1=f ( a[n] );
    k2=f ( a[n]+(h/2)*k1 );
    k3=f ( a[n]+(h/2)*k2 );
    k4=f ( a[n]+h*k3 ); 
    a[n+1]=(a[n]+(h/6)*(k1 + 2*k2 + 2*k3 + k4))

fo=open("a_of_t.txt", "w")
for item in a:
    fo.write("%e\n" % item)
fo.close()

plt.plot(t,a, 'k')
plt.show()

错误读取

line 23, in <module>
    k3=f ( a[n]+(h/2)*k2 );
line 15, in f
    c=((0.75/a + 0.044/(a**2) + 0.74*(a**2))**0.5)  
OverflowError: (34, 'Numerical result out of range')

【问题讨论】:

标签: python


【解决方案1】:

Python 小数存储为 64 位浮点数,因此具有有限精度。 10^-15 不能用浮点数表示。考虑使用decimal 模块。

【讨论】:

  • Python 使用双精度浮点数(64 位浮点数),其幅度范围约为 1e308 到 1e-308,足以满足 OP 规定的 1e-15 范围。
  • @James 你能建议我如何在这段代码中加入十进制模块吗?我不明白。
  • @user40330 只需通过 Decimal(var) 将所有变量转换为 Decimal。例如,T=Decimal(4.32*10**19)i=Decimal(input("Number of iterations "))。如果你想要一个 float 最后,只需使用 float(someDecimal) 进行投射。
  • @James 谢谢!帮助
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多