首页 > 解决方案 > Python:如何用 while 循环替换这个 for 循环?(没有负值)

问题描述

在定义炮弹函数的轨迹时,我希望循环在 y 的负值处停止。即炮弹落地后不应继续移动。

我尝试使用 while >= 0,但 y 点是一个列表,我不知道该怎么做。有什么帮助吗?

def trajectory(v_0=1, mass=1, theta=np.pi/2, t_0=0, t_f=2, n=100):
"""
:param v_0: initial velocity, in meters per second
:param mass: Mass of the object in kg, set to 1kg as default
:param theta: Angle of the trajectory's shot, set to pi/2 as default
:param t_0: initial time, in seconds, default as 0
:param t_f: final time, in seconds, default as 2
:param n: Number of points
:return: array with x and y coordinates of the trajectory
"""
h = (t_f - t_0)/n
t_points = np.arange(t_0, t_f, h)
x_points = []
y_points = []
r = np.array([0, v_0 * np.cos(theta), 0, v_0 * np.sin(theta)], float)

for t in t_points:
    x_points.append(r[0])
    y_points.append(r[2])
    k1 = h * F(r, t, mass)
    k2 = h * F(r + 0.5 * k1, t + 0.5 * h, mass)
    k3 = h * F(r + 0.5 * k2, t + 0.5 * h, mass)
    k4 = h * F(r + k3, t + h, mass)
    r += (k1 + 2 * k2 + 2 * k3 + k4) / 6
return np.array(x_points, float), np.array(y_points, float)

在绘制轨迹图时,我得到一个包含 y 负值的图形,我想首先防止它被计算,以免影响代码的性能。

标签: pythonloopsphysics

解决方案


您无需转换为while循环。我能想到的最简单的方法是在for循环中放置一个退出条件:

for t in t_points:
    if r[2] < 0:
        break
    ...

y位置小于零时,这将退出循环。您可以考虑设置条件r[2] < 0 and r[3] < 0,以便如果您有一个从地下开始,它会在下降并与地面相撞之前向上移动。

如果您真的将心放在while循环上,则可以创建一个迭代器变量,然后使用它来迭代t_points

iterator_variable = 0
while r[2] < 0 and iterator_variable < len(t_points):
    t = t_points[iterator_variable]
    ...
return np.array(x_points, float), np.array(y_points, float)

虽然我不知道您的功能是做什么的F(),但我认为不定义n,ht_points. 您将从起点开始,计算每个下一个点,直到落地。这种策略非常适合while循环。

while r[2] > 0:
    //calculate next position and velocity
    //add that position to the list of x_points and y_points

您可以将其作为点密度度量或最大点数,而不是n作为函数的输入来指示您计算的点数。


推荐阅读