Skip to content

Added forward euler in python3 #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions chapters/differential_equations/euler/code/python/euler.py
Original file line number Diff line number Diff line change
@@ -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()
4 changes: 4 additions & 0 deletions chapters/differential_equations/euler/euler.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 %}

<script>
Expand Down