嗨,我想集成一個功能從0到幾個不同的上限(約1000)。我已經寫了一段代碼來使用for循環並將每個值附加到一個空數組。但是我意識到我可以通過做更小的積分來使代碼更快,然後將以前的積分結果添加到剛剛計算的結果中。所以我會做相同數量的積分,但超過一個較小的區間,然後只需加上前面的積分即可得到從0到該上限的積分。繼承人我的代碼在這一刻:如何讓我的python集成更快?
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方法之前,Lv不會被初始化。 – Moustache