Skip to content

Thomas Algorithm in Javascript #647

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

Closed
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
41 changes: 41 additions & 0 deletions contents/thomas_algorithm/code/javascript/thomas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// note this example is inplace and destructive
thomas = (a, b, c, d) => {

// set the initial elements
c[0] = c[0] / b[0]
d[0] = d[0] / b[0]

n = d.length // number of equations to solve
for (i = 1; i < n; i++) {
scale = 1 / (b[i] - c[i-1] * a[i]) // scale factor for c and d
c[i] *= scale
d[i] = (d[i] - a[i] * d[i-1]) * scale
}

// do the back substitution
for (i = n-2; i >= 0; i--) {
d[i] -= c[i] * d[i+1]
}

return d
}

/*
example for matrix
[1 4 0][x] [7]
[2 3 5][y] = [5]
[0 3 6][z] [3]

[.8666]
soln will equal [1.533]
[-.266]
note we index a from 1 and c from 0
*/

a = [0, 2, 3]
b = [1, 3, 6]
c = [4, 5, 0]
d = [7, 5, 3]

soln = thomas(a, b, c, d)
console.log(soln)
2 changes: 2 additions & 0 deletions contents/thomas_algorithm/thomas_algorithm.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
[import, lang:"crystal"](code/crystal/thomas.cr)
{% sample lang="kotlin" %}
[import, lang:"kotlin"](code/kotlin/thomas.kt)
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/thomas.js)
{% endmethod %}

<script>
Expand Down