Runge Kutta 4和Python中的摆锤模拟

时间:2018-10-25 08:43:57

标签: python numpy scientific-computing runge-kutta

我正在尝试制作一个使用runge kutta 4绘制摆幅的python程序。我拥有的方程是角加速度np.where

请找到我的代码。我对python很陌生。

import numpy as np
df_cleaned_sessions['is_conversion'] = np.where(df_cleaned_sessions['datetime_only_first_engagement'].isin(df_cleaned_sessions['datetime_sessions']),True,False)

我现在更新了代码。我正正弦。 谢谢你。

2 个答案:

答案 0 :(得分:3)

您已应用RK4步骤,就像在求解一阶方程式一样。您需要将二阶方程转换为一阶系统,然后求解该耦合系统。

v = dy/dt
acceleration = dv/dt

因此RK4的每个步骤都有两个组成部分

k1y = h*v
k1v = h*accel(y)

k2y = h*(v+0.5*k1v)
k2v = h*accel(y+0.5*k1y)


完整的代码给出了一个很好的正弦波

import numpy as np 
import matplotlib.pyplot as plt 
m = 3.0
g = 9.8
r = 2.0
I = 12.0
h = 0.0025 
l=2.0
cycle = 10.0
t = np.arange(0, cycle, h)
# step height h 
n = len(t) 
initial_angle = 90.0
y=np.zeros(n)
v=np.zeros(n)
def accel(theta): return -(m*g*r/I)*np.sin(theta)
y[0] = np.radians(initial_angle) 
v[0] = np.radians(0.0)

for i in range(0, n-1): 
    k1y = h*v[i]
    k1v = h*accel(y[i])

    k2y = h*(v[i]+0.5*k1v)
    k2v = h*accel(y[i]+0.5*k1y)

    k3y = h*(v[i]+0.5*k2v)
    k3v = h*accel(y[i]+0.5*k2y)

    k4y = h*(v[i]+k3v)
    k4v = h*accel(y[i]+k3y)

    # Update next value of y 
    y[i+1] = y[i] + (k1y + 2 * k2y + 2 * k3y + k4y) / 6.0 
    v[i+1] = v[i] + (k1v + 2 * k2v + 2 * k3v + k4v) / 6.0

plt.plot(t, y)
plt.title('Pendulum Motion:')
plt.xlabel('time (s)')
plt.ylabel('angle (rad)')
plt.grid(True)
plt.show()

enter image description here

答案 1 :(得分:0)

import numpy as np 
import matplotlib.pyplot as plt 
m = 3.0
g = 9.8
r = 2.0
I = 12.0
h = 0.0025 
l=2.0
cycle = 10.0
t = np.arange(0, cycle, h)
# step height h 
n = len(t) 
initial_angle = 90.0
y=np.zeros(n)
v=np.zeros(n)
def accel(theta): return -(m*g*r/I)*np.sin(theta)
y[0] = np.radians(initial_angle) 
v[0] = np.radians(0.0)

for i in range(0, n-1): 
    k1y = h*v[i]
    k1v = h*accel(y[i])

    k2y = h*(v[i]+0.5*k1v)
    k2v = h*accel(y[i]+0.5*k1y)

    k3y = h*(v[i]+0.5*k2v)
    k3v = h*accel(y[i]+0.5*k2y)

    k4y = h*(v[i]+k3v)
    k4v = h*accel(y[i]+k3y)

    # Update next value of y 
    y[i+1] = y[i] + (k1y + 2 * k2y + 2 * k3y + k4y) / 6.0 
    v[i+1] = v[i] + (k1v + 2 * k2v + 2 * k3v + k4v) / 6.0

plt.plot(t, y)
plt.title('Pendulum Motion:')
plt.xlabel('time (s)')
plt.ylabel('angle (rad)')
plt.grid(True)
plt.show()