【发布时间】:2013-12-27 09:00:17
【问题描述】:
您好,我想将一个函数从 0 集成到几个不同的上限(大约 1000)。我已经编写了一段代码来使用 for 循环并将每个值附加到一个空数组中。但是我意识到我可以通过做更小的积分然后将先前的积分结果添加到刚刚计算的结果中来使代码更快。所以我会做相同数量的积分,但间隔更小,然后只需添加前一个积分即可获得从 0 到上限的积分。这是我目前的代码:
import numpy as np #importing all relevant modules and functions
from scipy.integrate import quad
import pylab as plt
import datetime
t0=datetime.datetime.now() #initial time
num=np.linspace(0,10,num=1000) #setting up array of values for t
Lt=np.array([]) #empty array that values for L(t) are appended to
def L(t): #defining function for L
return np.cos(2*np.pi*t)
for g in num: #setting up for loop to do integrals for L at the different values for t
Lval,x=quad(L,0,g) #using the quad function to get the values for L. quad takes the function, where to start the integral from, where to end the integration
Lv=np.append(Lv,[Lval]) #appending the different values for L at different values for t
我需要进行哪些更改才能执行我建议的优化技术?
【问题讨论】:
-
应该叫吕吗?否则 Lv 在调用 append 方法之前不会被初始化。
-
您可能还考虑使用 ctypes,我认为这也应该加快集成速度:docs.scipy.org/doc/scipy/reference/tutorial/…
标签: python optimization for-loop scipy physics