Python 运行时警告:除法中遇到无效值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14861891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RuntimeWarning: invalid value encountered in divide
提问by Bogdan Osyka
I have to make a program using Euler's method for the "ball in a spring" model
我必须使用欧拉的方法为“弹簧中的球”模型制作一个程序
from pylab import*
from math import*
m=0.1
Lo=1
tt=30
k=200
t=20
g=9.81
dt=0.01
n=int((ceil(t/dt)))
km=k/m
r0=[-5,5*sqrt(3)]
v0=[-5,5*sqrt(3)]
a=zeros((n,2))
r=zeros((n,2))
v=zeros((n,2))
t=zeros((n,2))
r[1,:]=r0
v[1,:]=v0
for i in range(n-1):
rr=dot(r[i,:],r[i,:])**0.5
a=-g+km*cos(tt)*(rr-L0)*r[i,:]/rr
v[i+1,:]=v[i,:]+a*dt
r[i+1,:]=r[i,:]+v[i+1,:]*dt
t[i+1]=t[i]+dt
#print norm(r[i,:])
plot(r[:,0],r[:,1])
xlim(-100,100)
ylim(-100,100)
xlabel('x [m]')
ylabel('y [m]')
show()
I keep getting this error:
我不断收到此错误:
a=-g+km*cos(tt)*(rr-L0)*r[i,:]/rr
RuntimeWarning: invalid value encountered in divide
I can't figure it out, what is wrong with the code?
看不懂,代码有什么问题?
采纳答案by Yan Zhu
I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:
我认为您的代码正在尝试“除以零”或“除以 NaN”。如果您知道这一点并且不希望它打扰您,那么您可以尝试:
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
For more details see:
有关更多详细信息,请参阅:
回答by crayzeewulf
You are dividing by rrwhich may be 0.0. Check if rris zero and do something reasonable other than using it in the denominator.
您正在除以rr可能是 0.0。检查是否rr为零并做一些合理的事情,而不是在分母中使用它。
回答by Kinch
Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second(i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
Python 索引从 0(而不是 1)开始,因此您的赋值“r[1,:] = r0”定义了 r 的第二个(即索引 1)元素,并将第一个(索引 0)元素保留为一对零。for 循环中 i 的第一个值是 0,因此 rr 得到 r 中第一个条目与其自身(即 0)的点积的平方根,并且在后续行中除以 rr 会引发错误。
回答by qrtLs
To prevent division by zero you could pre-initialize the output 'out' where the div0 error happens, eg np.wheredoes not cut it since the complete line is evaluated regardless of condition.
为了防止被零除,您可以在发生 div0 错误的地方预先初始化输出“out”,例如np.where,不切断它,因为无论条件如何都会评估完整的行。
example with pre-initialization:
预初始化示例:
a = np.arange(10).reshape(2,5)
a[1,3] = 0
print(a) #[[0 1 2 3 4], [5 6 7 0 9]]
a[0]/a[1] # errors at 3/0
out = np.ones( (5) ) #preinit
np.divide(a[0],a[1], out=out, where=a[1]!=0) #only divide nonzeros else 1

