-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspring-vertlet.py
52 lines (42 loc) · 1.06 KB
/
spring-vertlet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import matplotlib.pyplot as plt
# mass, spring constant, initial position and velocity
m = 1
k = 1
x = 0
v = 1
# simulation time, timestep and time
t_max = 100
# critical dt for Verlet stability appears to be 1.95
dt = 0.1
t_array = np.arange(0, t_max, dt)
# initialise empty lists to record trajectories
x_list = []
v_list = []
# Numerical integration
for t in t_array:
# append current state to trajectories
x_list.append(x)
v_list.append(v)
# calculate new position and velocity
a = -k * x / m
if t == 0:
# Euler integration
x = x + dt * v
v = v + dt * a
else:
# Verlet integration
x = 2*x - x_list[-2] + dt*dt*a
v = (x - x_list[-1])/dt
# convert trajectory lists into arrays, so they can be sliced (useful for Assignment 2)
x_array = np.array(x_list)
v_array = np.array(v_list)
# plot the position-time graph
plt.figure(1)
plt.clf()
plt.xlabel('time (s)')
plt.grid()
plt.plot(t_array, x_array, label='x (m)')
plt.plot(t_array, v_array, label='v (m/s)')
plt.legend()
plt.show()