简体   繁体   中英

Python: index error with numerical differentiation

In my code I am extracting the velocity and acceleration from time, position measurements and I am receiving an index error when performing numerical differentiation:

    VelocityVsTime = np.empty((2,0), float)

for i in range(1, len(PosVsTime[0])-1):
    velocity = (PosVsTime[1][i+1] - PosVsTime[1][i-1]) / (PosVsTime[0][i+1] - PosVsTime[0][i-1])
    VelocityVsTime = np.append(VelocityVsTime, [[PosVsTime[0][i]], [velocity]], axis = 1)
    
#print(VelocityVsTime)

AccelerationvsTime = np.empty((2,0), float)

for j in range(1, len(VelocityVsTime[1])-1):
    acceleration = (VelocityVsTime[1][i+1] - VelocityVsTime[1][i-1]) / (VelocityVsTime[0][i+1] - VelocityVsTime[0][i-1])
    AccelerationvsTime = np.append(AccelerationvsTime, [VelocityVsTime[0][i]], [acceleration], axis=1)
    
print(AccelerationvsTime)

The error is:

IndexError: index 50 is out of bounds for axis 0 with size 49

any tips on how to correct this? Thanks

heres the full code: the error occurs on line 42 where I declare the acceleration variable

import numpy as np

import matplotlib.pyplot as plt


PosVsTime = np.loadtxt("balldata.txt", delimiter=",").transpose()

#print(PosVsTime[0][0])

#t_0 = PosVsTime[0][0]

#pos_0 = PosVsTime[1][0]


#print("The initial state of this system at time = 0 is ", pos_0)


VelocityVsTime = np.empty((2,0), float)

for i in range(1, len(PosVsTime[0])-1):
    velocity = (PosVsTime[1][i+1] - PosVsTime[1][i-1]) / (PosVsTime[0][i+1] - PosVsTime[0][i-1])
    VelocityVsTime = np.append(VelocityVsTime, [[PosVsTime[0][i]], [velocity]], axis = 1)
    
#print(VelocityVsTime)

#plt.errorbar(VelocityVsTime[0], VelocityVsTime[1], fmt = '--k')

AccelerationvsTime = np.empty((2,0), float)

for j in range(1, len(VelocityVsTime[0])-1):
    #acceleration = (VelocityVsTime[1][i+1] - VelocityVsTime[1][i-1]) / (VelocityVsTime[0][i+1] - VelocityVsTime[0][i-1])
    #AccelerationvsTime = np.append(AccelerationvsTime, [VelocityVsTime[0][i]], [acceleration], axis=1)
    
print(AccelerationvsTime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM