开发者社区> 问答> 正文

一旦达到某个值,试图让循环停止,但它总是进行一步太多

正如标题所示。看一下代码块:

m = 100
a = -9.8
y0 = 30000
t0 = 0
v0 = 0
dt = 0.01

yAF = np.array([])
yAF = np.append(yAF, y0)

tAF = np.array([])
tAF = np.append(tAF, t0)

speedAF = np.array([])
speedAF = np.append(speedAF, v0)

def dy_dt(t):

return a * t 

i = 0

while yAF[i] >= 0:

i = i + 1
tAF = np.append(tAF, tAF[i-1] + dt)
speedAF = np.append(speedAF, dy_dt(tAF[i-1]))
yAF = np.append(yAF, yAF[i-1] + dt * dy_dt(tAF[i-1]))

正如你所看到的,我试图实现的条件是当值yAF [i]低于零时,我不想将它添加到数组中,我希望循环结束。

展开
收起
一码平川MACHEL 2019-01-16 17:27:27 1445 0
1 条回答
写回答
取消 提交回答
  • 您颠倒了检查和追加的顺序。你应该首先检查,然后才附加:

    yAF, yAF, speedAF = [], [], []
    yAF_next, tAF_next, speedFA_next = y0, t0, v0

    while yAF_next >= 0:

    yAF.append(yAF_next)
    tAF.append(t0_next)
    speedAF.append(speedFA_next)
    
    tAF_next = tAF[-1] + dt
    speedAF_next = dy_dt(tAF[-1])
    yAF_next = yAF[-1] + dt * dy_dt(tAF[-1])

    有趣的是,你甚至不需要i变量。是的,使用列表,稍后将它们转换为数组。

    2019-07-17 23:25:41
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
用计算和数据去改变整个世界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载