Skip to content

Commit 54b833b

Browse files
Butt4cak3PudottaPommin
authored andcommitted
Clean up Java implementation of Thomas Algorithm (#496)
1 parent 1f365b4 commit 54b833b

File tree

3 files changed

+44
-38
lines changed

3 files changed

+44
-38
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class Thomas {
2+
private static double[] thomasAlgorithm(double[] a, double[] b, double[] c, double[] x) {
3+
int size = a.length;
4+
double[] y = new double[size]; // This is needed so that we don't have to modify c
5+
double[] solution = new double[size];
6+
7+
// Set initial elements
8+
y[0] = c[0] / b[0];
9+
solution[0] = x[0] / b[0];
10+
11+
for (int i = 1; i < size; ++i) {
12+
// Scale factor is for c and x
13+
double scale = 1.0 / (b[i] - a[i] * y[i - 1]);
14+
y[i] = c[i] * scale;
15+
solution[i] = (x[i] - a[i] * solution[i - 1]) * scale;
16+
}
17+
18+
// Back-substitution
19+
for (int i = size - 2; i >= 0; --i) {
20+
solution[i] -= y[i] * solution[i + 1];
21+
}
22+
23+
return solution;
24+
}
25+
26+
public static void main(String[] args) {
27+
double[] a = {0.0, 2.0, 3.0};
28+
double[] b = {1.0, 3.0, 6.0};
29+
double[] c = {4.0, 5.0, 0.0};
30+
double[] x = {7.0, 5.0, 3.0};
31+
double[] solution = thomasAlgorithm(a, b, c, x);
32+
33+
System.out.format("The system,\n");
34+
System.out.format("[%.1f, %.1f, %.1f][x] = [%.1f]\n", b[0], c[0], 0f, x[0]);
35+
System.out.format("[%.1f, %.1f, %.1f][y] = [%.1f]\n", a[1], b[1], c[1], x[1]);
36+
System.out.format("[%.1f, %.1f, %.1f][z] = [%.1f]\n", 0f, a[2], b[2], x[2]);
37+
System.out.format("has the solution:\n");
38+
39+
for (int i = 0; i < solution.length; i++) {
40+
System.out.format("[% .5f]\n", solution[i]);
41+
}
42+
}
43+
}

contents/thomas_algorithm/code/java/thomas.java

Lines changed: 0 additions & 37 deletions
This file was deleted.

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
108108
<img class="center" src="code/scratch/thomas.svg" width="1000" />
109109
</p>
110110
{% sample lang="java" %}
111-
[import, lang:"java"](code/java/thomas.java)
111+
[import, lang:"java"](code/java/Thomas.java)
112112
{% sample lang="hs" %}
113113
[import, lang:"haskell"](code/haskell/thomas.hs)
114114
{% sample lang="go" %}

0 commit comments

Comments
 (0)