Skip to content

Commit c35ed42

Browse files
sklanButt4cak3
authored andcommitted
Added forward euler in python3 (#203)
1 parent a9ef5ff commit c35ed42

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import math
2+
3+
4+
def forward_euler(time_step, n):
5+
result = [0] * n
6+
result[0] = 1
7+
for i in range(1, n):
8+
result[i] = result[i - 1] - 3 * result[i - 1] * time_step
9+
return result
10+
11+
12+
def check(result, threshold, time_step):
13+
approx = True
14+
for i in range(len(result)):
15+
solution = math.exp(-3 * i * time_step)
16+
if abs(result[i] - solution) > threshold:
17+
print(result[i], solution)
18+
approx = False
19+
return approx
20+
21+
22+
def main():
23+
time_step = 0.01
24+
n = 100
25+
threshold = 0.01
26+
27+
result = forward_euler(time_step, n)
28+
approx = check(result, threshold, time_step)
29+
print("All values within threshold") if approx else print("Value(s) not in threshold")
30+
31+
main()

chapters/differential_equations/euler/euler.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ So, this time, let's remove ourselves from any physics and instead solve the fol
110110

111111
Full code for the visualization follows:
112112
[import, lang:"elm"](code/elm/euler.elm)
113+
114+
{% sample lang="py" %}
115+
### Python
116+
[import, lang:"python"](code/python/euler.py)
113117
{% endmethod %}
114118

115119
<script>

0 commit comments

Comments
 (0)