blablabla blablabla -3 years ago 102
Python Question

How to make my python integration faster?

Hi i want to integrate a function from 0 to several different upper limits (around 1000). I have written a piece of code to do this using a for loop and appending each value to an empty array. However i realise i could make the code faster by doing smaller integrals and then adding the previous integral result to the one just calculated. So i would be doing the same number of integrals, but over a smaller interval, then just adding the previous integral to get the integral from 0 to that upper limit. Heres my code at the moment:

import numpy as np #importing all relevant modules and functions
from scipy.integrate import quad
import pylab as plt
import datetime #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

What changes do I need to make to do the optimisation technique I've suggested?

Answer Source

Basically, we need to keep track of the previous values of Lval and g. 0 is a good initial value for both, since we want to start by adding 0 to the first integral, and 0 is the start of the interval. You can replace your for loop with this:

last, lastG = 0, 0
for g in num:
  Lval,x = quad(L, lastG, g)
  last, lastG = last + Lval, g

In my testing, this was noticeably faster.

As @askewchan points out in the comments, this is even faster:

Lv = []
last, lastG = 0, 0
for g in num:
  Lval,x = quad(L, lastG, g)
  last, lastG = last + Lval, g
Lv = np.array(Lv)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download