|
| 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 | +} |
0 commit comments