-
Notifications
You must be signed in to change notification settings - Fork 0
/
richardson2.py
executable file
·63 lines (51 loc) · 1.23 KB
/
richardson2.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
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
# Initial variables and constants.
y = 1
t = 0
h = 0.5
lamb = 2
# Equation `dy/dt = lamb * y`
tt = [t]
yy = [y]
yy1 = [y]
yy2 = [y]
yy4 = [y]
yyex = [y]
for k in range(2):
# Euler step.
y1 = y + h * (lamb * y)
# Two Euler half steps.
hh = h * 0.5
y2 = y
for _ in range(2):
y2 += hh * (lamb * y2)
# Four Euler quarter steps.
qh = h * 0.25
y4 = y
for _ in range(4):
y4 += qh * (lamb * y4)
# Richardson extrapolation (2-1) and (4-2)
yr1 = y2 + (y2 - y1) / (2 - 1)
yr2 = y4 + (y4 - y2) / (2 - 1)
# Richardson extrapolation of Richardson extrapolations
y = yr2 + (yr2 - yr1) / (2 ** 2 - 1)
t += h
tt.append(t)
yy1.append(y1)
yy2.append(y2)
yy4.append(y4)
yy.append(y)
yexact = np.exp(lamb * t)
yyex.append(yexact)
plt.figure(figsize=(4, 4))
plt.plot(tt, yy, marker='.', label='Richardson')
plt.plot(tt, yy4, marker='.', label='Euler h/4')
plt.plot(tt, yy2, marker='.', label='Euler h/2')
plt.plot(tt, yy1, marker='.', label='Euler h')
plt.plot(tt, yyex, label='exact', c='k')
plt.xlabel('t')
plt.ylabel('y')
plt.legend()
plt.savefig('richardson2.pdf', bbox_inches='tight')