首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python脚本w二阶龙格库塔方法求解摆的方程,我如何添加KE,PE和TE的计算?

使用Python脚本w二阶龙格库塔方法求解摆的方程,我如何添加KE,PE和TE的计算?
EN

Stack Overflow用户
提问于 2016-10-19 10:42:09
回答 1查看 1.4K关注 0票数 0

我不知道如何编写我的脚本来绘制KE、PE和TE。我在我觉得问题所在的部分代码中包含了多个###########。

代码语言:javascript
复制
def pendulum_runge_kutta(theta0,omega0,g,tfinal,dt):
    # initialize arrays
    t = np.arange(0.,tfinal+dt,dt)              # time array t
    npoints = len(t)
    theta = np.zeros(npoints)                   # position array theta
    omega = np.zeros(npoints)                   # position array omega
    Ke = np.zeros(npoints)
    Pe = np.zeros(npoints)
    L=4
    g = 9.81
    t2=np.linspace(0,tfinal,1000)
    theta0=0.01
    omega0=0

    # exact solution for 
    thetaExact = theta0*np.cos((g/L)**(1/2)*t2)

    # SECOND ORDER RUNGE_KUTTA SOLUTION
    theta[0] = theta0
    omega[0] = omega0
    #Ke[0] = #######################################
    #Pe[0] =###################################### 
    m=1.0
    for i in range(npoints-1):
        # compute midpoint position (not used!) and  velocity         
        thetamid = theta[i] + omega[i]*dt
        omegamid = omega[i] - (g/L)*np.sin(theta[i])*dt/2

        # use midpoint velocity to advance position            
        theta[i+1] = theta[i] + omegamid*dt
        omega[i+1] = omega[i] -(g/L)*np.sin(thetamid)*dt/2

        ###########calculate Ke, Pe, Te############
        Ke[i+1] =  0.5*m*(omega[i+1]*L)**2
        Pe[i+1] = m*g*L*np.sin(theta[i+1])
    Te = Ke+Pe

    #plot result of Ke, Pe, Te
    pl.figure(1)
    pl.plot(t,Ke,'c-',label='kinetic energy')
    pl.plot(t,Pe,'m-',label='potential energy')
    pl.plot(t,Te,'g-',label='total energy')
    pl.title('Ke, Pe, and Te')
    pl.legend(loc='lower right')
    pl.show()

    #now plot the results
    pl.figure(2)
    pl.plot(t,theta,'ro',label='2oRK')
    pl.plot(t2,thetaExact,'r',label='Exact')
    pl.grid('on')
    pl.legend()
    pl.xlabel('Time (s)')
    pl.ylabel('Theta')
    pl.title('Theta vs Time')
    pl.show()

#call function    
pendulum_runge_kutta(0.01, 0, 9.8, 12, .1)
EN

回答 1

Stack Overflow用户

发布于 2016-10-20 01:30:36

中点法的公式统一适用于一阶系统的所有构件。因此,对于中点值和全时间步长的全dt,它都应该是dt/2

势能应包含sin(x)C-cos(x)的积分。例如,

代码语言:javascript
复制
Pe[i+1] = m*g*L*(1-np.cos(theta[i+1]))

时间点i+1的能量公式也适用于时间点0。您必须将mass声明上移,例如,在length L=4行之后。

最后要说明的是,所示的精确解是针对小角度近似的,对于一般的物理摆,没有有限可表示的精确解。对于给定的theta0=0.01振幅,小角度近似应该足够好,但对于较大的摆动,请注意这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40121203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档