簡體   English   中英

Python擺錘

[英]Python pendulum

我試圖從Verlet算法中推導出擺方程。 這就是我使用Python所做的工作,其中r為擺角, w為速度, a為角加速度。 h是時間的增加,我的主要問題是,如果我引入的h小於2,則程序會一次又一次地向我顯示相同的數字。

from math import sin, cos, pi
from pylab import plot,show
h=int(input("h: "))
q=int(input("Angle: "))
l=int(input("Pendulum lenght: "))
r=q*pi/180 #Change the angle from degrees to rad
w=0
g=9.81
a=(-g/l)*sin(r)
y=0
xx=[]
yy=[]
while y>=0:
    r= r+h*w+ (h**2)/2*a
    x= cos(r) #Cartesians
    y= sin(r)
    w= w+ ((h/2)*a)
    a=(-g/l)*sin(r)
    w= w+((h/2)*a)
    xx.append(x)
    yy.append(y)
plot (xx,yy)
show()

對於任何物理上合理的擺,您的h都應小於1(秒)才能正確建模。 但是您要強制轉換為要舍入的int ,因此您得到h=0 (無時間步長)。 而是使用float

h=float(input("h: "))
q=float(input("Angle: "))
l=float(input("Pendulum length: "))

我不知道關於物理學的第一件事-xnx可能有您的答案。

但是,我可以建議您采用一種實用的編程方法嗎?

讓我們從封裝以下公式開始:

from math import sin, cos, pi
from pylab import plot,show

def getA(pLen, r):
    g = 9.81
    return (-g / pLen) * sin(r)

然后,我們需要使您程序的其余部分成為一個函數,以便我們稍后可以做一些非常有用的事情。

def main():
    h=int(input("h: "))
    q=int(input("Angle: "))
    l=int(input("Pendulum lenght: "))
    r=q*pi/180 #Change the angle from degrees to rad
    w=0
    a=getA(l, r)
    y=0
    xx=[]
    yy=[]
    while y>=0:
        r= r+h*w+ (h**2)/2*a
        x= cos(r) #Cartesians
        y= sin(r)
        w= w+ ((h/2)*a)
        a=getA(l, r)
        w= w+((h/2)*a)
        xx.append(x)
        yy.append(y)
    plot (xx,yy)
    show()

# call your main function only when running directly
if __name__ == '__main__':
    main()

現在,假設您的文件名為pendulum.py ,請跳至控制台並打開python shell:

>python
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pendulum
>>> pendulum.getA(5, 50)
0.5147794629671083
>>>

現在,您可以在桌面檢查您的getA()函數,以確保它為給定的輸入返回正確的輸出。

重復執行程序中的所有其他操作,您將能夠進一步隔離問題,這是解決問題的重要一步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM