Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
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

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

like image 352
blablabla Avatar asked Dec 10 '13 01:12

blablabla


People also ask

How do you use quad in Python?

quad() method, we can get the integration of a given function from limit a to b by using scipy. integrate. quad() method. Return : Return the integration of a polynomial.

What does Scipy Quad return?

The quad function returns the two values, in which the first number is the value of integral and the second value is the estimate of the absolute error in the value of integral.


1 Answers

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
  Lv=np.append(Lv,[last])

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.append(last)
Lv = np.array(Lv)
like image 88
Sam Mussmann Avatar answered Sep 22 '22 15:09

Sam Mussmann