From e5c1947ffa3b5cf2a8ff3259542a7dda9e50b9b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Antonio=20Hern=C3=A1ndez=20C=C3=A1novas?= Date: Tue, 9 Oct 2018 18:31:10 +0200 Subject: [PATCH 1/5] add thomas algorithm in javascript --- .../code/javascript/thomas.js | 31 +++++++++++++++++++ contents/thomas_algorithm/thomas_algorithm.md | 2 ++ 2 files changed, 33 insertions(+) create mode 100644 contents/thomas_algorithm/code/javascript/thomas.js diff --git a/contents/thomas_algorithm/code/javascript/thomas.js b/contents/thomas_algorithm/code/javascript/thomas.js new file mode 100644 index 000000000..fddab21d0 --- /dev/null +++ b/contents/thomas_algorithm/code/javascript/thomas.js @@ -0,0 +1,31 @@ +function thomas(a, b, c, x) { + let y = []; + + y[0] = c[0] / b[0]; + x[0] = x[0] / b[0]; + + for (let i = 1; i < a.length; i++) { + let scale = 1.0 / (b[i] - a[i] * y[i - 1]); + y[i] = c[i] * scale; + x[i] = (x[i] - a[i] * x[i - 1]) * scale; + } + + for (let i = a.length - 2; i >= 0; i--) + x[i] -= y[i] * x[i + 1]; +} + +let a = [0.0, 2.0, 3.0]; +let b = [1.0, 3.0, 6.0]; +let c = [4.0, 5.0, 0.0]; +let x = [7.0, 5.0, 3.0]; + +console.log("The system,"); +console.log("[1.0 4.0 0.0][x] = [7.0]"); +console.log("[2.0 3.0 5.0][y] = [5.0]"); +console.log("[0.0 3.0 6.0][z] = [3.0]"); +console.log("has the solution:\n"); + +thomas(a, b, c, x); + +for (let i = 0; i < 3; i++) + console.log("[" + x[i] + "]"); diff --git a/contents/thomas_algorithm/thomas_algorithm.md b/contents/thomas_algorithm/thomas_algorithm.md index 885739421..11f74f159 100644 --- a/contents/thomas_algorithm/thomas_algorithm.md +++ b/contents/thomas_algorithm/thomas_algorithm.md @@ -119,6 +119,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e [import, lang:"nim"](code/nim/thomas_algorithm.nim) {% sample lang="cpp" %} [import, lang:"c_cpp"](code/c++/thomas.cpp) +{% sample lang="js" %} +[import, lang:"javascript"](code/javascript/thomas.js) {% endmethod %}