Search code examples
pythonarraysnumpyscipynumerical-integration

Cumulative integration of elements of numpy arrays


I would like to to the following type of integration:

Say I have 2 arrays

a = np.array[1,2,3,4]
b = np.array[2,4,6,8]

I know how to integrate these using something like:

c = scipy.integrate.simps(b, a)

where c = 15 for above data set.

What I would like to do is multiply the first elements of each array and add to new array called d, i.e. a[0]*b[0] then integrate the first 2 elements the arrays then the first 3 elements, etc. So eventually for this data set, I would get

d = [2 3 8 15]

I have tried a few things but no luck; I am pretty new to writing code.


Solution

  • If I have understood correctly what you need you could do the following:

    import numpy as np
    from scipy import integrate
    
    a = np.array([2,4,6,8])
    b = np.array([1,2,3,4])
    d = np.empty_like(b)
    d[0] = a[0] * b[0]
    for i in range(2, len(a) + 1):
        d[i-1] = integrate.simps(b[0:i], a[0:i])
    print(d)