Skip to content

Commit 532f7cf

Browse files
authored
Thomas algorithm implementation in Common Lisp (#604)
1 parent 691a7e4 commit 532f7cf

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
;;;; Thomas algorithm implementation in Common Lisp
2+
3+
(defmacro divf (place divisor)
4+
"Divides the value at place by divisor"
5+
`(setf ,place (/ ,place ,divisor)))
6+
7+
(defun helper (v1 v2 v3 row)
8+
(- (svref v1 row) (* (svref v2 row) (svref v3 (1- row)))))
9+
10+
(defun thomas (diagonal-a diagonal-b diagonal-c last-column)
11+
"Returns the solutions to a tri-diagonal matrix non-destructively"
12+
;; We have to copy the inputs to ensure non-destructiveness
13+
(let ((a (copy-seq diagonal-a))
14+
(b (copy-seq diagonal-b))
15+
(c (copy-seq diagonal-c))
16+
(d (copy-seq last-column)))
17+
(divf (svref c 0) (svref b 0))
18+
(divf (svref d 0) (svref b 0))
19+
(loop
20+
for i from 1 upto (1- (length a)) do
21+
(divf (svref c i) (helper b a c i))
22+
(setf (svref d i) (/ (helper d a d i) (helper b a c i))))
23+
(loop
24+
for i from (- (length a) 2) downto 0 do
25+
(decf (svref d i) (* (svref c i) (svref d (1+ i)))))
26+
d))
27+
28+
(defparameter diagonal-a #(0 2 3))
29+
(defparameter diagonal-b #(1 3 6))
30+
(defparameter diagonal-c #(4 5 0))
31+
(defparameter last-column #(7 5 3))
32+
33+
;; should print 0.8666667 1.5333333 -0.26666668
34+
(format t "~{~f ~}~%" (coerce (thomas diagonal-a diagonal-b diagonal-c last-column) 'list))

contents/thomas_algorithm/thomas_algorithm.md

+2
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
129129
[import, lang:"crystal"](code/crystal/thomas.cr)
130130
{% sample lang="kotlin" %}
131131
[import, lang:"kotlin"](code/kotlin/thomas.kt)
132+
{% sample lang="lisp" %}
133+
[import, lang:"lisp"](code/clisp/thomas.lisp)
132134
{% sample lang="ruby" %}
133135
[import, lang="ruby"](code/ruby/thomas.rb)
134136
{% sample lang="js" %}

0 commit comments

Comments
 (0)