Andre
Andre

Reputation: 712

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

Upvotes: 3

Views: 15785

Answers (2)

Lior Cohen
Lior Cohen

Reputation: 5745

You just need to sum in a simple for loop.

dv = a*dt

dx = 0.5*a*dt^2

Note - I wrote this code w/o checking it, so there may be some syntax errors

v = [0]  # or whatever you initial velocity is
x = [0]  # or whatever you initial location is
dt = 1.0 # or your time interval

for a in [1, 2, 3, 4, 5]:
    v.append(v[-1] + a*dt)
    x.append(x[-1] + 0.5*a*dt**2)
print(v)
print(x)

Upvotes: -1

Banghua Zhao
Banghua Zhao

Reputation: 1556

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.

Upvotes: 4

Related Questions