-
Notifications
You must be signed in to change notification settings - Fork 0
/
finite_diff_wave_eqn (RK2 update).py
64 lines (50 loc) · 1.22 KB
/
finite_diff_wave_eqn (RK2 update).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
53
54
55
56
57
58
59
60
61
62
63
64
"""
Uses 3 point central scheme for calculating derivative on RHS
"""
import numpy as np
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
########## code here
c = 1
delta = 0.0001
L = 5
N = 1000
h = L/N
tfinal = 3
xs = np.linspace(0, L, N)
init = np.exp(-32*(xs-4)**2)
f = np.zeros((N+2))
f_mid = np.zeros((N+2))
f[1:N+1] = init
f[0] = f[N]
f[-1] = f[1]
writeint = 0
t = 0
while t <= tfinal:
# RK2
f_mid[1:N+1] = f[1:N+1] - (c*delta/(4*h))*(f[2:N+2] - f[0:N])
f_mid[0] = f_mid[N]
f_mid[-1] = f_mid[1]
f[1:N+1] = f[1:N+1] - (c*delta/(2*h))*(f_mid[2:N+2] - f_mid[0:N])
f[0] = f[N]
f[-1] = f[1]
# Upwind (euler backward) - stable
# f[1:N+1] = f[1:N+1] - (c*delta/h)*(f_mid[1:N+1] - f_mid[0:N])
# f[0] = f[N]
# f[-1] = f[1]
# Central Diff + Euler Forward (unstable)
# f[1:N+1] = f[1:N+1] - (c*delta/(2*h))*(f_mid[2:N+2] - f_mid[0:N])
# f[0] = f[N]
# f[-1] = f[1]
t = np.round(t, 5)
if t >= writeint:
plt.plot(xs, f[1:N+1], label='t={}'.format(round(t, 2)))
plt.xlabel('x')
plt.ylabel('psi(x, t)')
plt.grid()
plt.legend()
writeint += 1
t += delta
plt.show()