pythonlistscipynumerical-integrationintegral

Integrating a list of values in Python


I have a list of data, which represents acceleration. For simplicity, let's say this list is:

X = [1, 2, 3, 4, 5]

I want to integrate each value in this list twice (double integration) so I can retrieve information about location.

Quick reminder: position, velocity, and acceleration are related. You can find acceleration by taking the derivative twice. Or, you can take the integral twice if you start with acceleration.

I cannot really change the data I am working with. I have floating point values stored in a list coming from my accelerometer. I also understand that usually, integration requires a function to be defined, typically with a variable that can be integrated over an interval.

I have tried using the library:

import scipy.integrate as integrate 

and have attempted using the .quad method, but I am yielding errors.

I would love any tips, ideas, or links to resources that could help.

Github repo


Solution

  • Use .cumtrapz method. cumtrapz(X) computes the approximate cumulative integral of X via the trapezoidal method with unit spacing.

    import scipy.integrate as it
    X = [1, 2, 3, 4, 5]
    velocity = it.cumtrapz(X,initial=0)
    location = it.cumtrapz(velocity,initial=0)
    print 'velocity: ', velocity
    print 'location: ', location
    

    Output:

    velocity:  [  0.    1.5   4.    7.5  12. ]
    location:  [  0.     0.75   3.5    9.25  19.  ]
    

    Note if your have the time vector t corresponding to acceleration vector, you need to use cumtrapz(X,t). Here is the reference for method cumtrapz.