Python 索引错误:索引 10000 超出轴 0 的范围,大小为 10000
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34316403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IndexError: index 10000 is out of bounds for axis 0 with size 10000
提问by Stephen Ryan
For my physics degree, I have to take some Python lessons. I'm an absolute beginner and as such, I can't understand other answers. The code is to plot an object's trajectory with air resistance. I would really appreciate a quick fix - I think it has something to do with the time variable being too small but increasing it doesn't help.
对于我的物理学位,我必须上一些 Python 课程。我是一个绝对的初学者,因此,我无法理解其他答案。代码是用空气阻力绘制物体的轨迹。我真的很感激快速修复 - 我认为这与时间变量太小有关,但增加它无济于事。
import matplotlib.pyplot as plt
import numpy as np
import math # need math module for trigonometric functions
g = 9.81 #gravitational constant
dt = 1e-3 #integration time step (delta t)
v0 = 40 # initial speed at t = 0
angle = math.pi/4 #math.pi = 3.14, launch angle in radians
time = np.arange(0, 10, dt) #time axis
vx0 = math.cos(angle)*v0 # starting velocity along x axis
vy0 = math.sin(angle)*v0 # starting velocity along y axis
xa = vx0*time # compute x coordinates
ya = -0.5*g*time**2 + vy0*time # compute y coordinates
def traj_fric(angle, v0): # function for trajectory
vx0 = math.cos(angle) * v0 # for some launch angle and starting velocity
vy0 = math.sin(angle) * v0 # compute x and y component of starting velocity
x = np.zeros(len(time)) #initialise x and y arrays
y = np.zeros(len(time))
x[0], y[0], 0 #projecitle starts at 0,0
x[1], y[1] = x[0] + vx0 * dt, y[0] + vy0 * dt # second elements of x and
# y are determined by initial
# velocity
i = 1
while y[i] >= 0: # conditional loop continuous until
# projectile hits ground
gamma = 0.005 # constant of friction
height = 100 # height at which air friction disappears
f = 0.5 * gamma * (height - y[i]) * dt
x[i + 1] = (2 * x[i] - x[i - 1] + f * x[i - 1])/1 + f # numerical integration to find x[i + 1]
y[i + 1] = (2 * y[i] - y[i - 1] + f * y[i - 1] - g * dt ** 2)/ 1 + f # and y[i + 1]
i = i + 1 # increment i for next loop
x = x[0:i+1] # truncate x and y arrays
y = y[0:i+1]
return x, y, (dt*i), x[i] # return x, y, flight time, range of projectile
x, y, duration, distance = traj_fric(angle, v0)
fig1 = plt.figure()
plt.plot(xa, ya) # plot y versus x
plt.xlabel ("x")
plt.ylabel ("y")
plt.ylim(0, max(ya)+max(ya)*0.2)
plt.xlim(0, distance+distance*0.1)
plt.show()
print "Distance:" ,distance
print "Duration:" ,duration
n = 5
angles = np.linspace(0, math.pi/2, n)
maxrange = np.zeros(n)
for i in range(n):
x,y, duration, maxrange [i] = traj_fric(angles[i], v0)
angles = angles/2/math.pi*360 #convert rad to degress
print "Optimum angle:", angles[np.where(maxrange==np.max(maxrange))]
The error is:
错误是:
File "C:/Python27/Lib/site-packages/xy/projectile_fric.py", line 43, in traj_fric x[i + 1] = (2 * x[i] - x[i - 1] + f * x[i - 1])/1 + f # numerical integration to find x[i + 1]
IndexError: index 10000 is out of bounds for axis 0 with size 10000
文件“C:/Python27/Lib/site-packages/xy/projectile_fric.py”,第 43 行,在 traj_fric x[i + 1] = (2 * x[i] - x[i - 1] + f * x [i - 1])/1 + f # 数值积分找到 x[i + 1]
索引错误:索引 10000 超出轴 0 的范围,大小为 10000
采纳答案by Mason Wheeler
This is pretty straightforward. When you have a size of 10000
, element index 10000
is out of bounds because indexing begins with 0
, not 1
. Therefore, the 10,000th element is index 9999
, and anything larger than that is out of bounds.
这很简单。当您的大小为 时10000
,元素索引10000
超出范围,因为索引以 开头0
,而不是1
。因此,第 10,000 个元素是 index 9999
,任何大于此值的元素都是越界的。
回答by John R. Strohm
Mason Wheeler's answer told you what Python was telling you. The problem occurs in this loop:
Mason Wheeler 的回答告诉您 Python 告诉您的内容。问题出现在这个循环中:
while y[i] >= 0: # conditional loop continuous until
# projectile hits ground
gamma = 0.005 # constant of friction
height = 100 # height at which air friction disappears
f = 0.5 * gamma * (height - y[i]) * dt
x[i + 1] = (2 * x[i] - x[i - 1] + f * x[i - 1])/1 + f # numerical integration to find x[i + 1]
y[i + 1] = (2 * y[i] - y[i - 1] + f * y[i - 1] - g * dt ** 2)/ 1 + f # and y[i + 1]
i = i + 1 # increment i for next loop
The simple fix is to change the loop to something like (I don't know Python syntax, so bear with me):
简单的解决方法是将循环更改为类似(我不知道 Python 语法,所以请耐心等待):
while (y[i] >= 0) and (i < len(time)):
That will stop the sim when you run out of array, but it will (potentially) also stop the sim with the projectile hanging in mid-air.
当你用完阵列时,这将停止模拟,但它也会(可能)停止模拟,射弹悬挂在半空中。
What you have here is a very simple ballistic projectile simulation, modeling atmospheric friction as a linear function of altitude. QUALITATIVELY, what is happening is that your projectile is not hitting the ground in the time you allowed, and you are attempting to overrun your tracking arrays. This is caused by failure to allow sufficient time-of-flight. Observe that the greatest possible time-of-flight occurs when atmospheric friction is zero, and it is then trivial to compute a closed-form upper bound for time-of-flight. You then use that upper bound as your time, and you will allocate sufficient array space to simulate the projectile all the way to impact.
您在这里拥有的是一个非常简单的弹道模拟,将大气摩擦建模为高度的线性函数。定性地说,正在发生的事情是您的射弹没有在您允许的时间内击中地面,并且您正试图超越您的跟踪阵列。这是由于未能允许足够的飞行时间造成的。观察到最大可能的飞行时间发生在大气摩擦为零时,然后计算飞行时间的封闭形式上限是微不足道的。然后您使用该上限作为您的时间,您将分配足够的阵列空间来模拟射弹一直到撞击的过程。