[英]Python: How can I substitute this for loop with a while loop? (No negative values)
在定義炮彈 function 的軌跡時,我希望循環在 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 負值的圖形,我想首先防止它被計算,以免影響代碼的性能。
您無需轉換為while
循環。 我能想到的最簡單的方法是在for
循環中放置一個退出條件:
for t in t_points:
if r[2] < 0:
break
...
當y
position 小於零時,這將退出循環。 您可能會考慮使條件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)
雖然我不知道您的 function F()
做了什么,但我認為 go 不定義n
、 h
或t_points
可能更容易。 您將從起點開始,計算每個下一個點,直到落地。 這種策略非常適合while
循環。
while r[2] > 0:
//calculate next position and velocity
//add that position to the list of x_points and y_points
而不是n
作為 function 的輸入,它指示您計算的點數,您可以將它作為點密度度量或最大點數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.