Skip to content

Forward euler implementation in Common Lisp #607

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 5 commits into from
May 24, 2020
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
29 changes: 29 additions & 0 deletions contents/forward_euler_method/code/clisp/euler.lisp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
;;;; Forward euler implementation in Common Lisp

(defun solve-euler (timestep n)
"Returns a function where y'(t) = -3t and y(0) = 0 using the forward euler method"
(loop
with result = (make-array n :initial-element 1)
for i from 1 upto (1- n) do
(setf (svref result i) (- (svref result (1- i)) (* 3 (svref result (1- i)) timestep)))
finally (return result)))

(defun approximatep (result threshold timestep)
"Checks the result from the solve-euler function"
(loop
with approximatep = t
with solution = 0
for i from 0 upto (1- (length result)) do
(setf solution (exp (* (- 3) i timestep)))
(when (> (- (svref result i) solution) threshold)
(setf approximatep nil)
(format t "~d ~d~%" (svref result i) solution))
finally (return approximatep)))

(defvar timestep 0.01)
(defvar n 100) ; number of steps
(defvar threshold 0.01)

(defvar result (solve-euler timestep n))
(defvar approximatep (approximatep result threshold timestep))
(format t "~:[Value(s) not in threshold~;All values within threshold~]~%" approximatep)
2 changes: 2 additions & 0 deletions contents/forward_euler_method/forward_euler_method.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ Full code for the visualization follows:
[import, lang:"java"](code/java/ForwardEuler.java)
{% sample lang="nim" %}
[import, lang:"nim"](code/nim/forwardeuler.nim)
{% sample lang="lisp" %}
[import, lang="lisp"](code/clisp/euler.lisp)
{% endmethod %}

<script>
Expand Down