弹丸运动模拟,索引越界错误,嵌套 for/while 循环

Projectile motion sim, index out of bounds error, nested for/while loops

我正在尝试绘制作为质量函数的最佳发射角度并绘制它。 对于 mlist 的每个元素,我希望它为 thetalist 的每个元素计算 m 的行进距离,然后取 m 的最高距离并获得 theta给出了答案并制作了一个新列表,其中包含所谓的 theta_optimum 并将其与 mlist 进行对比。

这是我的代码:

import matplotlib.pylab as plt
import numpy as np
import math
#############
Die = 10.0
B = 1.6e-4
b = B*Die
g = 9.81
tmax = 1000
dt = 0.01
v = 100.0
mlist = np.arange(1.0, 100.0, 1.0)
thetalist = np.arange(0.1, math.pi / 2.0, 0.1)
theta_op = []

for j in range(len(mlist)):
    for i in range(len(thetalist)):
        vy = math.sin(thetalist[i]) * v
        vx = math.cos(thetalist[i]) * v
        t = 0.0
        x = 0.0
        y = 0.0
        xlist = []
        while y >= 0.0:
            vx1 = -b/mlist[j]*vx
            vx = vx + vx1*dt
            dx = vx * dt
            x = x + dx

            vy1 = -g-b/mlist[j]*vy
            vy = vy + vy1 * dt
            dy = vy * dt
            y = y + dy

            t = t + dt

            xlist.append(x)

        theta_op.append(thetalist[xlist.index(max(xlist))])

plt.plot(mlist, theta_op, color='red')
plt.show()

我得到的错误是:

line 39, in <module>
theta_op.append(thetalist[xlist.index(max(xlist))])
IndexError: index 202 is out of bounds for axis 0 with size 15

我的问题是如何修复我的代码中的这个错误以及它为什么会出现。我知道物理学是正确的,但由于我是编码新手,我不确定我制作列表和循环的方式是否正确。我已经寻找过类似的其他问题,但没有找到。

看起来你严重混淆了你的变量范围。

对于质量和 theta 的每个值,您在积分过程中保存 每个 x 值。假设这就是您想要做的,那么您编写了导致此错误的行:

theta_op.append(thetalist[xlist.index(max(xlist))])

上面returns中最大值的索引xlist;然后您使用该索引访问 thetalist,这使得 完全没有意义 thetalistxlist的大小是独立的,前者取决于theta步长,后者取决于仿真时间步长;所以使用一个的索引访问另一个可能会导致溢出。

这让我们回到了为什么首先要保存所有 x 值的问题。为什么不直接保存每个 theta 值的 last x 值,并获得每个质量的最佳 theta,这与您的问题描述完全匹配?

for j in range(len(mlist)):

    best_theta = 0.0
    best_x = 0.0

    for i in range(len(thetalist)):

        # initialisation code as before
        # ...

        while y >= 0.0:
            # integration code as before
            # ...

        # update the best theta for this mass
        if x > best_x:
            best_theta = thetalist[i]
            best_x = x

    # add the best theta to theta_op without having to do any searches   
    theta_op.append(best_theta)

编辑:我用各种 theta 步长值测试了这段代码,所有结果都在 zero-resistance 限制的合理范围内(45 度 = 0.785398 ...弧度),所以不妨考虑增加风阻系数。