Skip to content

Added Thomas Algorithm in Haskell #321

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 1 commit into from
Aug 3, 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
18 changes: 18 additions & 0 deletions contents/thomas_algorithm/code/haskell/thomas.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Data.List (zip4)
import Data.Ratio

thomas :: Fractional a => [a] -> [a] -> [a] -> [a] -> [a]
thomas a b c = init . scanr back 0 . tail . scanl forward (0, 0) . zip4 a b c
where
forward (c', d') (a, b, c, d) =
let denominator = b - a * c'
in (c / denominator, (d - a * d') / denominator)
back (c, d) x = d - c * x

main :: IO ()
main = do
let a = [0, 2, 3] :: [Ratio Int]
b = [1, 3, 6]
c = [4, 5, 0]
d = [7, 5, 3]
print $ thomas a b c d
5 changes: 3 additions & 2 deletions contents/thomas_algorithm/thomas_algorithm.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ In the end, we will update $$c$$ and $$d$$ to be $$c'$$ and $$d'$$ like so:
$$
\begin{align}
c'_i &= \frac{c_i}{b_i - a_i \times c'_{i-1}} \\
d'_i &= \frac{d_i - a_i*d'_{i-1}}{b_i - a_i \times c'_{i-1}}
d'_i &= \frac{d_i - a_i \times d'_{i-1}}{b_i - a_i \times c'_{i-1}}
\end{align}
$$

Expand All @@ -44,6 +44,8 @@ $$
[import, lang:"c_cpp"](code/c/thomas.c)
{% sample lang="py" %}
[import, lang:"python"](code/python/thomas.py)
{% sample lang="hs" %}
[import, lang:"haskell"](code/haskell/thomas.hs)
{% endmethod %}

This is a much simpler implementation than Gaussian Elimination and only has one for loop before back-substitution, which is why it has a better complexity case.
Expand All @@ -70,4 +72,3 @@ $$
\newcommand{\bfomega}{\boldsymbol{\omega}}
\newcommand{\bftau}{\boldsymbol{\tau}}
$$