Skip to content

Commit fb14e81

Browse files
authored
Forward euler implementation in Common Lisp (#607)
1 parent efcb278 commit fb14e81

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
;;;; Forward euler implementation in Common Lisp
2+
3+
(defun solve-euler (timestep n)
4+
"Returns a function where y'(t) = -3t and y(0) = 0 using the forward euler method"
5+
(loop
6+
with result = (make-array n :initial-element 1)
7+
for i from 1 upto (1- n) do
8+
(setf (svref result i) (- (svref result (1- i)) (* 3 (svref result (1- i)) timestep)))
9+
finally (return result)))
10+
11+
(defun approximatep (result threshold timestep)
12+
"Checks the result from the solve-euler function"
13+
(loop
14+
with approximatep = t
15+
with solution = 0
16+
for i from 0 upto (1- (length result)) do
17+
(setf solution (exp (* (- 3) i timestep)))
18+
(when (> (- (svref result i) solution) threshold)
19+
(setf approximatep nil)
20+
(format t "~d ~d~%" (svref result i) solution))
21+
finally (return approximatep)))
22+
23+
(defvar timestep 0.01)
24+
(defvar n 100) ; number of steps
25+
(defvar threshold 0.01)
26+
27+
(defvar result (solve-euler timestep n))
28+
(defvar approximatep (approximatep result threshold timestep))
29+
(format t "~:[Value(s) not in threshold~;All values within threshold~]~%" approximatep)

contents/forward_euler_method/forward_euler_method.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ Full code for the visualization follows:
144144
[import, lang:"java"](code/java/ForwardEuler.java)
145145
{% sample lang="nim" %}
146146
[import, lang:"nim"](code/nim/forwardeuler.nim)
147+
{% sample lang="lisp" %}
148+
[import, lang="lisp"](code/clisp/euler.lisp)
147149
{% endmethod %}
148150

149151
<script>

0 commit comments

Comments
 (0)