Search code examples
pythonarraysnumpyscipynumerical-integration

Integrate a function with each element of numpy arrays as limit of integration


I have a function in python (using scipy and numpy also) defined as

import numpy as np
from scipy import integrate
LCDMf = lambda x: 1.0/np.sqrt(0.3*(1+x)**3+0.7)

I would like to integrate it from 0 to each element in a numpy array say z = np.arange(0,100)

I know I can write a loop for each element iterating through like

an=integrate.quad(LCDMf,0,z[i])

But, I was wondering if there is a faster, efficient (and simpler) way to do this with each numpy element.


Solution

  • After tinkering with np.vectorize I found the following solution. Simple - elegant and it works!

    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]
    

    This method works with unsorted float arrays or anything we throw at it and doesn't any initial conditions as in the odeint method.

    I hope this helps someone somewhere too... Thanks all for your inputs.