-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathharmonic_oscillator.py
46 lines (41 loc) · 1.31 KB
/
harmonic_oscillator.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
import numpy as np
import matplotlib.pyplot as plt
m=1; k=1; dt=0.01; n_step=1000
v=0; x=1
v_vector = np.zeros(n_step)
x_vector = np.zeros(n_step)
for step in range(n_step):
v = v + (dt/2) * (-k * x / m)
x = x + dt * v
v = v + (dt/2) * (-k * x / m)
v_vector[step] = v
x_vector[step] = x
plt.figure()
plt.plot(np.arange(1, n_step+1) * dt, x_vector, linewidth=2)
plt.plot(np.arange(1, n_step+1) * dt, v_vector, '--', linewidth=2)
plt.xlabel('time')
plt.ylabel('position or velocity')
plt.legend(['position', 'velocity'])
plt.tight_layout()
plt.savefig('fig-c01-position_and_momentum.pdf')
plt.close()
potential = 0.5 * k * x_vector**2
kinetic = 0.5 * m * v_vector**2
plt.figure()
plt.plot(np.arange(1, n_step+1) * dt, potential, linewidth=2)
plt.plot(np.arange(1, n_step+1) * dt, kinetic, '--', linewidth=2)
plt.plot(np.arange(1, n_step+1) * dt, potential + kinetic, '-.', linewidth=1)
plt.xlabel('time')
plt.ylabel('Energy')
plt.legend(['potential', 'kinetic', 'total'])
plt.tight_layout()
plt.savefig('fig-c01-energy_conservation.pdf')
plt.close()
plt.figure(figsize=(5,4.8))
plt.plot(x_vector, v_vector, '.', markersize=10)
plt.xlabel('position')
plt.ylabel('momentum')
plt.axis('equal')
plt.tight_layout()
plt.savefig('fig-c01-phase_space.pdf', dpi=200)
plt.close()