Euler method
1
func euler_method(t0, t1, k, step_size) {
2
var results = [[0, t0]]
3
for s in (step_size..100 -> by(step_size)) {
4
t0 -= ((t0 - t1) * k * step_size)
5
results << [s, t0]
6
}
7
return results;
8
}
9
10
func analytical(t0, t1, k, time) {
11
(t0 - t1) * exp(-time * k) + t1
12
}
13
14
var (T0, T1, k) = (100, 20, .07)
15
var r2 = euler_method(T0, T1, k, 2).grep { _[0] %% 10 }
16
var r5 = euler_method(T0, T1, k, 5).grep { _[0] %% 10 }
17
var r10 = euler_method(T0, T1, k, 10).grep { _[0] %% 10 }
18
19
say "Time\t 2 err(%) 5 err(%) 10 err(%) Analytic"
20
say "-"*76
21
22
r2.range.each { |i|
23
var an = analytical(T0, T1, k, r2[i][0])
24
printf("%4d\t#{'%9.3f' * 7}\n",
25
r2[i][0],
26
r2[i][1], ( r2[i][1] / an) * 100 - 100,
27
r5[i][1], ( r5[i][1] / an) * 100 - 100,
28
r10[i][1], (r10[i][1] / an) * 100 - 100,
29
an)
30
}
Copied!

Output:

1
Time 2 err(%) 5 err(%) 10 err(%) Analytic
2
----------------------------------------------------------------------------
3
0 100.000 0.000 100.000 0.000 100.000 0.000 100.000
4
10 57.634 -3.504 53.800 -9.923 44.000 -26.331 59.727
5
20 37.704 -5.094 34.281 -13.711 27.200 -31.534 39.728
6
30 28.328 -4.927 26.034 -12.629 22.160 -25.629 29.797
7
40 23.918 -3.808 22.549 -9.313 20.648 -16.959 24.865
8
50 21.843 -2.555 21.077 -5.972 20.194 -9.910 22.416
9
60 20.867 -1.569 20.455 -3.512 20.058 -5.384 21.200
10
70 20.408 -0.912 20.192 -1.959 20.017 -2.808 20.596
11
80 20.192 -0.512 20.081 -1.057 20.005 -1.432 20.296
12
90 20.090 -0.281 20.034 -0.559 20.002 -0.721 20.147
13
100 20.042 -0.152 20.014 -0.291 20.000 -0.361 20.073
Copied!
Last modified 1yr ago
Copy link
Contents
Output: