Roh*_*mar 5 python arrays numpy integrate scipy
我在 python 中有一个函数(也使用 scipy 和 numpy)定义为
import numpy as np
from scipy import integrate
LCDMf = lambda x: 1.0/np.sqrt(0.3*(1+x)**3+0.7)
Run Code Online (Sandbox Code Playgroud)
我想将它从 0 整合到 numpy 数组中的每个元素z = np.arange(0,100)
我知道我可以为每个元素编写一个循环,像这样迭代
an=integrate.quad(LCDMf,0,z[i])
Run Code Online (Sandbox Code Playgroud)
但是,我想知道是否有一种更快、更有效(更简单)的方法来对每个 numpy 元素执行此操作。
您可以将问题重新表述为 ODE。
然后该odeint函数可用于计算F(z)一系列z.
>>> scipy.integrate.odeint(lambda y, t: LCDMf(t), 0, [0, 1, 2, 5, 8])
array([[ 0. ], # integrate until z = 0 (must exist, to provide initial value)
[ 0.77142712], # integrate until z = 1
[ 1.20947123], # integrate until z = 2
[ 1.81550912], # integrate until z = 5
[ 2.0881925 ]]) # integrate until z = 8
Run Code Online (Sandbox Code Playgroud)
经过一番修改,np.vectorize我找到了以下解决方案。简单-优雅而且有效!
import numpy as np
from scipy import integrate
LCDMf = lambda x: 1.0/math.sqrt(0.3*(1+x)**3+0.7)
np.vectorize(LCDMf)
def LCDMfint(z):
return integrate.quad(LCDMf, 0, z)
LCDMfint=np.vectorize(LCDMfint)
z=np.arange(0,100)
an=LCDMfint(z)
print an[0]
Run Code Online (Sandbox Code Playgroud)
此方法适用于未排序的浮点数组或我们向其抛出的任何内容,并且没有像 odeint 方法中那样的任何初始条件。
我希望这对某个地方的人也有帮助...感谢大家的投入。