RuntimeWarning: invalid value encountered in divide

前端 未结 4 1744
野的像风
野的像风 2021-01-30 06:00

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         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 06:42

    To prevent division by zero you could pre-initialize the output 'out' where the div0 error happens, eg np.where does not cut it since the complete line is evaluated regardless of condition.

    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
    

提交回复
热议问题