首页 > 解决方案 > 如何在代码中修复“IndexError:标量变量的无效索引”

问题描述

import numpy as np

import matplotlib.pyplot as plt
M = 1.0 # Mass of discus in kg
g = 9.81 # Acceleration due to gravity (m/s^2)
V = 30 # Initial velocity in m/s
ang = 30 # Angle of initial velocity in degrees
Cd = 0.54 # Drag coefficient
Cl = 0.87
dt = 0.01 # time step in s
t = [0]
vx = [V*np.cos(ang/180*np.pi)]
vy = [V*np.sin(ang/180*np.pi)]
x = [0]
y = [1.8]
rho = 1.2 #density in kg/m^3
a_ref = 0.025 #area in m^2
gamma = 35/180*np.pi


drag=0.5 * rho * V**2 * a_ref * Cd
lift = 0.5 * rho * V**2 * a_ref * Cl
ax = ((rho*V**2*a_ref)/(2*M))*(-Cl *np.sin(gamma) - Cd * np.cos(gamma))
ay = ((rho*V**2*a_ref)/(2*M))*(Cl* np.cos(gamma) - Cd* np.sin(gamma)) -g

counter = 0

while (y[counter] >= 0):
    t.append(t[counter]+dt)
    vx.append(vx[counter]+dt*ax[counter])
    vy.append(vy[counter]+dt*ay[counter])
    x.append(x[counter]+dt*vx[counter])
    y.append(y[counter]+dt*vy[counter])
    vel = np.sqrt(vx[counter+1]**2 + vy[counter+1]**2)
    drag = 0.5 * rho * V**2 * a_ref * Cd
    lift = 0.5 * rho * V**2 * a_ref * Cl
    ax.append(((rho*V**2*a_ref)/(2*M))*(-Cl *np.sin(gamma) - Cd * np.cos(gamma)))
    ay.append(((rho*V**2*a_ref)/(2*M))*(Cl* np.cos(gamma) - Cd* np.sin(gamma)) -g)
    counter = counter +1

plt.plot(x,y,'ro')
plt.title("Womens Discus!")
plt.ylabel("y (m)")
plt.xlabel("x (m)")

我需要在“ vx.append(vx[counter]+dt*ax[counter])”行中修复此错误,但我对如何以及一直盯着这个问题几个小时一无所知。我不被允许附上我的整个代码(太长),所以我只是删除了变量和一些方程。

如果我需要添加任何内容以帮助解决此问题,请告诉我任何帮助将不胜感激。TIA

标签: pythonphysicsindex-error

解决方案


该错误是由您尝试索引变量引起的ax。这个变量是一个 numpy 标量,所以它不能被索引。


推荐阅读