Skip to content

Commit b5be893

Browse files
sklanleios
authored andcommitted
Thomas algorithm in java (#285)
* Add thomas algorithm in java * Update thomas_algorithm.md * Remove redundant blank line
1 parent 61cf9ef commit b5be893

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public class thomas {
2+
private static void thomasAlgorithm(double a[], double b[], double c[], double x[], int size) {
3+
4+
double y[] = new double[size];
5+
6+
y[0] = c[0] / b[0];
7+
x[0] = x[0] / b[0];
8+
9+
for (int i = 1; i < size; ++i) {
10+
double scale = 1.0 / (b[i] - a[i] * y[i - 1]);
11+
y[i] = c[i] * scale;
12+
x[i] = (x[i] - a[i] * x[i - 1]) * scale;
13+
}
14+
15+
for (int i = size - 2; i >= 0; --i) {
16+
x[i] -= y[i] * x[i + 1];
17+
}
18+
}
19+
20+
public static void main(String[] args) {
21+
double a[] = {0.0, 2.0, 3.0};
22+
double b[] = {1.0, 3.0, 6.0};
23+
double c[] = {4.0, 5.0, 0.0};
24+
double x[] = {7.0, 5.0, 3.0};
25+
26+
System.out.println("The system,\n");
27+
System.out.println("[1.0 4.0 0.0][x] = [7.0]\n");
28+
System.out.println("[2.0 3.0 5.0][y] = [5.0]\n");
29+
System.out.println("[0.0 3.0 6.0][z] = [3.0]\n");
30+
System.out.println("has the solution:\n");
31+
32+
thomasAlgorithm(a, b, c, x, 3);
33+
34+
for (int i = 0; i < 3; ++i)
35+
System.out.println("[" + x[i] + "]\n");
36+
}
37+
}

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ The transformations are quite easy too, isn't that neat?
102102
[import, lang:"c_cpp"](code/c/thomas.c)
103103
{% sample lang="py" %}
104104
[import, lang:"python"](code/python/thomas.py)
105+
{% sample lang="java" %}
106+
[import, lang:"java"](code/java/thomas.java)
105107
{% sample lang="hs" %}
106108
[import, lang:"haskell"](code/haskell/thomas.hs)
107109
{% endmethod %}

0 commit comments

Comments
 (0)