diff --git a/chapters/differential_equations/euler/code/python/euler.py b/chapters/differential_equations/euler/code/python/euler.py new file mode 100644 index 000000000..993be5b95 --- /dev/null +++ b/chapters/differential_equations/euler/code/python/euler.py @@ -0,0 +1,31 @@ +import math + + +def forward_euler(time_step, n): + result = [0] * n + result[0] = 1 + for i in range(1, n): + result[i] = result[i - 1] - 3 * result[i - 1] * time_step + return result + + +def check(result, threshold, time_step): + approx = True + for i in range(len(result)): + solution = math.exp(-3 * i * time_step) + if abs(result[i] - solution) > threshold: + print(result[i], solution) + approx = False + return approx + + +def main(): + time_step = 0.01 + n = 100 + threshold = 0.01 + + result = forward_euler(time_step, n) + approx = check(result, threshold, time_step) + print("All values within threshold") if approx else print("Value(s) not in threshold") + +main() diff --git a/chapters/differential_equations/euler/euler.md b/chapters/differential_equations/euler/euler.md index 2ce9a63de..40e195c9c 100644 --- a/chapters/differential_equations/euler/euler.md +++ b/chapters/differential_equations/euler/euler.md @@ -110,6 +110,10 @@ So, this time, let's remove ourselves from any physics and instead solve the fol Full code for the visualization follows: [import, lang:"elm"](code/elm/euler.elm) + +{% sample lang="py" %} +### Python +[import, lang:"python"](code/python/euler.py) {% endmethod %}