Doesbaddel
Doesbaddel

Reputation: 224

Trapeze Integration with Python

I want to do trapeze integration. Here is my code:

import numpy as n
import matplotlib.pyplot as plt
import math as m
import loaddataa as ld
import scipy.integrate as integrate 

dataListStride = ld.loadData("../Data/Fabienne")
indexStrideData = 0 #Daten ohne Gyrometer
strideData = dataListStride[indexStrideData]

def horizontal(yAngle, yAcceleration, xAcceleration):
    a = (m.cos(yAngle)*yAcceleration)-(m.sin(yAngle)*xAcceleration)
    return a

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))

resultsHorizontal.insert(0, 0)

print("The values are: " +str(resultsHorizontal))

print("Es gibt " +str(len(resultsHorizontal)) + " Werte.")

scale_factor = 0.01
x_values = np.arange(len(resultsHorizontal)) * scale_factor
plt.plot(x_values, resultsHorizontal)

Here you can see the current output and the desired additions I want to make to the output: output

In the red box on the picture you can see what I want to do next. Is there a way to make this easier in the form of a loop for example?

I've tried it with: integrate.cumtrapz(resultsHorizontal, dx=0.01) Then I get a list with 150 values again, like it should be. Unfortunately only the first value is correct and the rest is not. So I have to do it in an other way.

It should be like this: I want to do the trapeze integration from 0 to the first value (of the calculated values in the list resultsHorizontal. You can see it in the picture), then from the first value to the second, then from the second to the third, and so on, until the penultimate to last value. So that in the end I have the same number of values as in the list resultsHorizontal.

Upvotes: 0

Views: 205

Answers (1)

David Wierichs
David Wierichs

Reputation: 545

If I understand you correctly, you want to compute single trapezoidal areas between successive values of the array (Correct me if I'm wrong). For this, you could just manually compute (assuming from the image that dx is constant and that the values are stored in arr)

trapz = [(arr[i]+arr[i+1])/2*dx for i in range(len(arr)-1)]

This list will of course be shorter by one element than the list arr because there are only N-1 intervals between N points. If you insist on getting N values for the areas, please specify further how you would do this (I think there is ambiguity, in particular at the boundaries). With numpy one could also abbreviate the above as

trapz = (arr[:-1]+arr[1:])/2*dx

Upvotes: 1

Related Questions