簡體   English   中英

使用odeint()在Python中進行擺錘模擬不能完全起到擺錘的作用

[英]Pendulum simulation in Python using odeint() not quite working as a pendulum

我使用四階Runge-Kutta微分建立了擺錘仿真,其中所有步驟都是逐步完成的:

from scipy import *
from matplotlib.pyplot import *
##A pendulum simulation using fourth order 
##Runge-Kutta differentiation

ts=.05 #time step size
td=20 #trial duration
te=int(td/ts) #no of timesteps

mu=0.1 #friction factor
m=1 #mass
g=9.81 #grav. acceleration
l=1 #length

th=[((rand()*2)-1)*pi] #initial angle
om=[0] #initial angular velocity
u=0 #torque

for j in range(te):
    #Euler approximation
    th.append(th[j] + ts*om[j])
    f1 = (-mu*om[j] + m*g*l*sin(th[j]) + u)/(m*(l^2))
    om.append(om[j] + ts*f1)

    #approximation 1 at mid-interval
    th2 = th[j+1] + (ts/2)*om[j+1]
    f2 = (-mu*om[j+1] + m*g*l*sin(th[j+1]) + u)/(m*(l^2))
    om2 = om[j+1] + (ts/2)*f2

    #approximation 2 at mid-interval
    th3 = th2 + (ts/2)*om2
    f3 = (-mu*om2 + m*g*l*sin(th2) + u)/( m*(l^2))
    om3 = om2 + (ts/2)*f3

    #approximation at next time step
    th4 = th3 + (ts)*om3
    f4 = (-mu*om3 + m*g*l*sin(th3) + u)/( m*(l^2))
    om4 = om3 + (ts)*f4

    dth=(om[j] + 2*om[j+1] + 2*om2 + om3)/6
    dom=(f1 + 2*f2 + 2*f3 + f4)/6
    th[j+1] = th[j] + ts*dth
    om[j+1] = om[j] + ts*dom

subplot(211),plot(th),xlabel('Angle'),ylabel('')
subplot(212),plot(om,'r'),xlabel('Angular velocity'),ylabel('')
show()

這很好用,但是我覺得不太優雅,這就是為什么我決定使用odeint()函數重寫它的原因:

from scipy import integrate
from scipy import *
from matplotlib.pyplot import *
##A pendulum simulation

th=((rand()*2)-1)*pi #initial angle
om=0 #initial angular velocity
u=0 #torque

y0 = [om, th] #initial values
t = linspace(0, 20, 400) #

def f(y, t):
    mu=0.1 #friction factor
    m=1 #mass
    g=9.81 #grav. acceleration
    l=1 #length

    return (y[0],
        (-mu*y[0] + m*g*l*sin(y[1]) + u)/(m*(l^2)))


r = integrate.odeint(f, y0, t)

subplot(211),plot(t,r[:,1]),xlabel('Angle'),ylabel('')
subplot(212),plot(t,r[:,0],'r'),xlabel('Angular velocity'),ylabel('')
show()

而且這個新版本看起來不像鍾擺。 誰能告訴我我在做什么錯?

您的微分功能在擺運動方面有錯誤。

在python中, ^是異或運算符,而不是冪運算符** 因此,您將使用l ** 2。 同樣,AFAICT,狀態向量的第一個元素實際上應該是y [1]。 從過去的類似工作中可以得出結論(假設m = 1和l = 1)。

def simple_pendulum_deriv(x, t, g = 9.81, mu = 0.5): 
    nx = np.zeros(2)
    nx[0] = x[1]
    nx[1] = -(g * np.sin(x[0])) - mu*x[1]
    return nx

暫無
暫無

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

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