【问题标题】:How to make a condition to terminate appending?如何设定终止追加的条件?
【发布时间】:2020-11-26 17:08:27
【问题描述】:

我正在编写一个代码来绘制 Python 中各种 theta 值的几个弹丸轨迹。

theta = np.arange(np.pi/6, np.pi/3)
t = np.linspace(0,2,num=100)
while y0>=0:
    for i in theta:
        x = []
        y = []
        for k in t:
                x0= v_0*np.cos(i)*k
                y0= v_0*np.sin(i)*k - 1/2*g*(k**2)
                x.append(x0)
                x.append(y0)

在形成数组并放入弹丸的必要条件后,我使用了一个while循环将终止指令放入程序中。我想,我错过了一个关键点。谢谢!

【问题讨论】:

    标签: python projectile


    【解决方案1】:

    我认为您希望您的终止条件位于最内层循环中。见下文,我还定义了几个缺失的常量(v_0g)并将一个x 固定为y。也打印结果

    theta = np.arange(np.pi/6, np.pi/3)
    t = np.linspace(0,2,num=100)
    v_0 = 1
    g=10
    
    for i in theta:
        x = []
        y = []
        for k in t:
            x0= v_0*np.cos(i)*k
            y0= v_0*np.sin(i)*k - 1/2*g*(k**2)
            x.append(x0)
            y.append(y0)
            if y0 < 0: # the main change here. Stop looping when y_0 below zero
                break
        print(f'theta:{i}')
        print(f'x:{x}')    
        print(f'y:{y}')
    

    生产

    theta:0.5235987755982988
    x:[0.0, 0.017495462702715934, 0.03499092540543187, 0.052486388108147805, 0.06998185081086374, 0.08747731351357968]
    y:[0.0, 0.008060401999795939, 0.012039587797163551, 0.011937557392102841, 0.007754310784613805, -0.0005101520253035577]
    

    绘制它(y vs x),看起来很合理

    还值得注意的是,您对theta = np.arange(np.pi/6, np.pi/3) 的定义看起来很奇怪,您想在这里实现什么?

    【讨论】:

    • 我正在尝试为必须运行的程序创建一系列 Theta 值。因此,第一个 for 循环在连续的时间间隔内迭代 theta 值(由第二个 for 循环完成)。
    • @Manu 那么你也应该包含一个步骤,否则 step=1 这不太可能是你想要的。所以设置例如theta = np.arange(np.pi/6, np.pi/3, np.pi/24)
    • 哦,谢谢,我想我明白了。但问题是,为什么我们只得到一张图,而不是三个 thetas 值的三个轨迹?
    • 您应该将绘图命令放在print(...)statements 所在的位置,自然具有相同的偏移量,这将对theta 的每个值执行
    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2010-09-13
    • 1970-01-01
    • 2022-01-26
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多