python - 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 负值的图形,我想首先防止它被计算,以免影响代码的性能。
解决方案
您无需转换为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
,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
作为函数的输入来指示您计算的点数。
推荐阅读
- java - 2 Quartz 作业同时更新数据库中的相同值导致不一致的行为
- java - 如何从自定义 LinkedList 类继承?
- r - 插入符号的训练函数中的 PCA 预处理参数
- kdb - 统一列表漂亮打印机
- google-bigquery - BigQuery 无效的字段名称 _PARTITIONDATE 或 _PARTITIONTIME
- postgresql - 在 postgresql 中不使用 typeorm 的 typescript 之间的日期时间
- javascript - 在页面加载时显示全屏 gif,并在 gif 完成后关闭它
- linux - 无法找到默认 shell 为 bash 的常规文件,但当它是 ksh 时可以工作
- linux - 在 Bash 脚本中将文件内容作为密码参数传递
- matlab - 制定没有图像的 MatLab 深度神经网络