索引错误:索引 x 超出轴 0 的范围,大小为 x

时间:2021-05-23 18:26:16

标签: python matplotlib numerical-methods numerical-integration index-error

当我收集了时间的加速度函数时,我将绘制时间的速度函数。 但是,我得到一个错误代码,IndexError: index 51 is out of bounds for axis 0 with size 51,51 是我数据的最后一个索引,因为我的数据是这样设置的:f.write(str(akselerasjon) + " "+ str(tid) + "\n"),在 MicroPython 中收集它。但是,错误发生在我处理数据的 python 中。

这是我的代码:

# -*- coding: utf-8 -*-
"""
Created on Sat May 22 21:04:05 2021

@author: Petter Jansen Ytterdahl
"""

from matplotlib import pyplot as plt
import numpy as np

def rektangelmetoden(aks, tid):
    a_v = len(tid)
    vm = [0]
    t_v = 0
    
    for i in range(a_v - 1):
        h = tid[i + 1] - tid[i]
        t_v += aks[i] * h
        vm.append(t_v)
    return(vm)    

f = np.loadtxt("målinger.txt", float, skiprows = 0)
acceleration = f[:, 0]
time = f[:, 1]

gravitational_acceleration = 9.81 
mass = 0.5
k = 0.01 

m_v = []
m_t = []
t_start = 0
t_end = 5
steps = 1000
length_steps = (t_end-t_start)/(steps-1) 
 
velocity = np.zeros(steps) 
time = np.zeros(steps) 

for i in range(steps-1):
    velocity[i+1] = velocity[i] + length_steps * (gravitational_acceleration - k * velocity[i]**2 / mass)
    time[i+1] = time[i] + length_steps 

velocity_r = rektangelmetoden(acceleration, time)

plt.plot(time, velocity, color = "b", label = "Teoretisk modell")
plt.plot(time, velocity_r, color = "r", label = "målinger")
plt.xlabel("Time [s]")
plt.ylabel("Velocity [m/s]")
plt.title("Micro:Bit in parachute")
plt.grid()
plt.legend()

错误发生在这一行(第 18 行):

t_v += aks[i] * h

我确实在 Stackoverflow 上看到了其他一些类似的错误,但我太笨了,无法理解其中的大部分,所以请帮忙,谢谢。

3 个答案:

答案 0 :(得分:0)

尝试将您的代码更改为:

import DayPickerInput from 'react-day-picker/DayPickerInput';

<DayPickerInput  inputProps={{'aria-label':'Date input 2'}} />

我只是添加了一个 try/except 块来捕获索引错误并跳出 # -*- coding: utf-8 -*- """ Created on Sat May 22 21:04:05 2021 @author: Petter Jansen Ytterdahl """ from matplotlib import pyplot as plt import numpy as np def rektangelmetoden(aks, tid): a_v = len(tid) vm = [0] t_v = 0 for i in range(a_v - 1): try: h = tid[i + 1] - tid[i] t_v += aks[i] * h vm.append(t_v) except IndexError: break return(vm) f = np.loadtxt("målinger.txt", float, skiprows=0) acceleration = f[:, 0] time = f[:, 1] gravitational_acceleration = 9.81 mass = 0.5 k = 0.01 m_v = [] m_t = [] t_start = 0 t_end = 5 steps = 1000 length_steps = (t_end-t_start)/(steps-1) velocity = np.zeros(steps) time = np.zeros(steps) for i in range(steps-1): velocity[i+1] = velocity[i] + length_steps * \ (gravitational_acceleration - k * velocity[i]**2 / mass) time[i+1] = time[i] + length_steps velocity_r = rektangelmetoden(acceleration, time) plt.plot(time, velocity, color="b", label="Teoretisk modell") plt.plot(time, velocity_r, color="r", label="målinger") plt.xlabel("Time [s]") plt.ylabel("Velocity [m/s]") plt.title("Micro:Bit in parachute") plt.grid() plt.legend()

答案 1 :(得分:0)

第一件事是您使用了导数,因此您的加速度数据比速度数据少一个点。在迭代之前,您可以像 aks.insert(0, 0) 一样在加速度数组的开头(0-index)添加一个 0 值。

现在,您手动执行的代码中有很多事情在 numpy.js 中基本上是单行的。以下是我的建议:

from matplotlib import pyplot as plt
import numpy as np
from scipy.integrate import cumtrapz

# Calculate experimental velocity.
f = np.loadtxt("målinger.txt", float, skiprows=0)
acceleration_r = f[:, 0]
time_r = f[:, 1]
velocity_r = cumtrapz(acceleration_r, time_r, initial=0)

# Time array.
# I thought you'd like measured and theoretical times to automatically start and end at the same spots. 
t_start = time_r[0]
t_end = time_r[-1]
STEPS = 1000
time = np.linspace(t_start, t_end, STEPS, endpoint=True)
dt = time[1] - time[0]

# Calculate theoretical velocity.
g = 9.81
m = 0.5
k = 0.01
velocity = np.zeros(steps)
for i in range(steps-1):
    velocity[i+1] = velocity[i] + dt*(g - k*velocity[i]**2/m)

# Plot and compare both velocities.
fig, ax = plt.subplots()
fig.show()
ax.plot(time, velocity, color = "b", label = "Teoretisk modell")
ax.plot(time_r, velocity_r, color = "r", label = "målinger")
ax.set_xlabel("Time [s]")
ax.set_ylabel("Velocity [m/s]")
ax.set_title("Micro:Bit in parachute")
ax.grid()
ax.legend()

请注意,我使用的是 scipy.integrate.cumtrapz 而不是您自己的函数 (rektangelmetoden),但两者都面临失去一分的问题。 Scipy 使用 initial=0 关键字修复了这个问题,该关键字为速度添加了一个初始值,并将其恢复为与加速度和时间数组相同的长度。

答案 2 :(得分:0)

您的错误是您使用了 time 两次,一次从文件中读取,一次为参考解决方案构建它,长度无关。但是,在第二个之后,您尝试在第一个的上下文中再次使用该数组,结果是预料之中的。

为时间数组指定不同的名称,time_filetime_ref 或您想象的名称。