【问题标题】:divide by zero encountered in true_divide + invalid value encountered in true_divide + invalid value encountered in reduce在 true_divide 中遇到除以零 + 在 true_divide 中遇到无效值 + 在 reduce 中遇到无效值
【发布时间】:2019-01-18 13:54:28
【问题描述】:

这是我尝试根据温度和距离的变化绘制半Planck law 的内容,如下所示。

import numpy as np

k = 1.381*np.power(10,-23, dtype=np.float)
c = 3*np.power(10,8)
h = 6.626*np.power(10,-34, dtype=np.float)  
l = 3*np.power(10,-6, dtype=np.float)

d_lower = 16*np.power(10,4)
d_upper = 2*np.power(10,6)

t_lower = 740
t_upper = 5200

d = np.arange(d_lower,d_upper,100)
t = np.arange(t_lower,t_upper,10)
D,T = np.meshgrid(d, t)
I = (2*h*np.power(c,2))/(np.power(D,2)*np.power(l,5)*(np.exp((h*c)/(l*k*T))-1))  

解释器返回如下错误:

RuntimeWarning: divide by zero encountered in true_divide
  I = (2*h*np.power(c,2))/(np.power(D,2)*np.power(l,5)*(np.exp((h*c)/(l*k*T))-1))

我不应该遇到任何被零除的情况,因为T 的值是开尔文,所以np.exp((h*c)/(l*k*T))-1 不能变成零。

这里有什么问题?!

我的 python 和 numpy 版本分别是 3.7.01.15.4

【问题讨论】:

  • 代码对我来说工作正常,没有任何警告或错误产生不同的情节(不确定它是否是你想要的)。我正在使用 matplotlib 2.2.2 和 python 3.6.5。你用的是什么版本?
  • @Bazingaa:我的python是3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)],我的matplotlib是3.0.2
  • This 是我得到的
  • 这个问题似乎可以通过使用浮点数组d = np.arange(d_lower,d_upper,100.) (d.dtype == float64) 而不是整数数组d = np.arange(d_lower,d_upper,100) (d.dtype == int32) 来解决。我目前不知道为什么会导致这个问题。
  • 假设您在一个平台(可能是 Windows)上,numpy 整数数组的默认数据类型是 32 位 (np.int32)。表达式np.power(D, 2) 是使用D 的数据类型计算的,因此其结果的类型为np.int32。但是,该结果中的确切值大于 32 位整数可以表示的值,因此值溢出并可能变为负数或零。例如,np.array([106000, 1638400], dtype=np.int32)**2 返回array([-1648901888, 0], dtype=int32)。 @ImportanceOfBeingErnest 建议使用浮点数将解决问题。

标签: python numpy divide-by-zero


【解决方案1】:

问题可能是因为它是矩阵除法,python处理得不是很好。

尝试替换:

I = (2*h*np.power(c,2))/(np.power(D,2)np.power(l,5)(np.exp(( hc)/(lk*T))-1))

作者:

aaa = (2*h*np.power(c,2))
bbb = (np.power(D,2)*np.power(l,5)*(np.exp((h*c)/(l*k*T))-1))  
I = aaa/bbb

它对我有用

SLP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2020-11-11
    • 2018-02-04
    • 2017-07-14
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多