-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomework_1_file_without_loop
More file actions
50 lines (42 loc) · 2.46 KB
/
Copy pathHomework_1_file_without_loop
File metadata and controls
50 lines (42 loc) · 2.46 KB
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
import numpy as np
import matplotlib.pyplot as plt
class AdamsIntegrator:
def __init__(self, n_steps, start, stop):
self.n_steps, self.start, self.stop = n_steps, start, stop
self.h_step = (stop - start) / n_steps
self.h_step2 = self.h_step / n_steps
self.independent_var = np.linspace(start, stop, n_steps + 1)
self.dependent_var = np.zeros_like(self.independent_var)
def adams_function(self, t, y):
return (t - y) / 2
def runge_kutta(self, t, y):
k0 = self.h_step * self.adams_function(t, y)
k1 = self.h_step * self.adams_function(t + self.h_step / 2, y + k0 / 2)
k2 = self.h_step * self.adams_function(t + self.h_step / 2, y + k1 / 2)
k3 = self.h_step * self.adams_function(t + self.h_step, y + k2)
return y + (1 / 6) * (k0 + 2 * k1 + 2 * k2 + k3)
def adams_bashforth_calculator(self):
self.dependent_var[0] = 1
for k in range(1, 4):
self.dependent_var[k] = self.runge_kutta(self.independent_var[k - 1], self.dependent_var[k - 1])
for k in range(3, self.n_steps):
p = self.dependent_var[k] + self.h_step2 * (
-9 * self.adams_function(self.independent_var[k], self.dependent_var[k])
+ 37 * self.adams_function(self.independent_var[k - 1], self.dependent_var[k - 1])
- 59 * self.adams_function(self.independent_var[k - 2], self.dependent_var[k - 2])
+ 55 * self.adams_function(self.independent_var[k - 3], self.dependent_var[k - 3])
)
self.independent_var[k + 1] = self.start + self.h_step * (k + 1)
self.dependent_var[k + 1] = self.runge_kutta(self.independent_var[k], self.dependent_var[k])
def get_final_result(self):
self.adams_bashforth_calculator()
ysol = 3 * np.exp(-self.independent_var / 2) - 2 + self.independent_var
print("{: >3} {: >4} {: >15} {: >10}".format("k", "t", "Y numerical", "Y exact"))
for k in range(self.n_steps + 1):
print("{: 3d},{: 5.3f},{: 12.11f},{: 12.11f}".format(k, self.independent_var[k], self.dependent_var[k], ysol[k]))
plt.plot(self.independent_var[: self.n_steps + 1], self.dependent_var[: self.n_steps + 1], "o")
plt.plot(self.independent_var[: self.n_steps + 1], ysol[: self.n_steps + 1])
plt.show()
if __name__ == "__main__":
integrator = AdamsIntegrator(n_steps=24, start=0, stop=3)
integrator.get_final_result()