Skip to content

Commit 42ce0a5

Browse files
committed
added code
1 parent 9fffa08 commit 42ce0a5

File tree

2 files changed

+656
-178
lines changed

2 files changed

+656
-178
lines changed

doc/pub/week47/ipynb/rungekutta.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
2+
import numpy as np
3+
import pandas as pd
4+
from math import *
5+
import matplotlib.pyplot as plt
6+
import os
7+
8+
# Where to save the figures and data files
9+
PROJECT_ROOT_DIR = "Results"
10+
FIGURE_ID = "Results/FigureFiles"
11+
DATA_ID = "DataFiles/"
12+
13+
if not os.path.exists(PROJECT_ROOT_DIR):
14+
os.mkdir(PROJECT_ROOT_DIR)
15+
16+
if not os.path.exists(FIGURE_ID):
17+
os.makedirs(FIGURE_ID)
18+
19+
if not os.path.exists(DATA_ID):
20+
os.makedirs(DATA_ID)
21+
22+
def image_path(fig_id):
23+
return os.path.join(FIGURE_ID, fig_id)
24+
25+
def data_path(dat_id):
26+
return os.path.join(DATA_ID, dat_id)
27+
28+
def save_fig(fig_id):
29+
plt.savefig(image_path(fig_id) + ".png", format='png')
30+
31+
32+
def SpringForce(v,x,t):
33+
# note here that we have divided by mass and we return the acceleration
34+
return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)
35+
36+
37+
def RK4(v,x,t,n,Force):
38+
for i in range(n-1):
39+
# Setting up k1
40+
k1x = DeltaT*v[i]
41+
k1v = DeltaT*Force(v[i],x[i],t[i])
42+
# Setting up k2
43+
vv = v[i]+k1v*0.5
44+
xx = x[i]+k1x*0.5
45+
k2x = DeltaT*vv
46+
k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)
47+
# Setting up k3
48+
vv = v[i]+k2v*0.5
49+
xx = x[i]+k2x*0.5
50+
k3x = DeltaT*vv
51+
k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)
52+
# Setting up k4
53+
vv = v[i]+k3v
54+
xx = x[i]+k3x
55+
k4x = DeltaT*vv
56+
k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)
57+
# Final result
58+
x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.
59+
v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.
60+
t[i+1] = t[i] + DeltaT
61+
62+
63+
# Main part begins here
64+
65+
DeltaT = 0.001
66+
#set up arrays
67+
tfinal = 20 # in dimensionless time
68+
n = ceil(tfinal/DeltaT)
69+
# set up arrays for t, v, and x
70+
t = np.zeros(n)
71+
v = np.zeros(n)
72+
x = np.zeros(n)
73+
# Initial conditions (can change to more than one dim)
74+
x0 = 1.0
75+
v0 = 0.0
76+
x[0] = x0
77+
v[0] = v0
78+
gamma = 0.2
79+
Omegatilde = 0.5
80+
Ftilde = 1.0
81+
# Start integrating using Euler's method
82+
# Note that we define the force function as a SpringForce
83+
RK4(v,x,t,n,SpringForce)
84+
85+
# Plot position as function of time
86+
fig, ax = plt.subplots()
87+
ax.set_ylabel('x[m]')
88+
ax.set_xlabel('t[s]')
89+
ax.plot(t, x)
90+
fig.tight_layout()
91+
save_fig("ForcedBlockRK4")
92+
plt.show()

0 commit comments

Comments
 (0)