11,488,764 members (75,458 online)
alternative version

# la4j - Linear Algebra for Java

, 14 Nov 2011 CPOL 11K 242 7
Elegant and pure Java matrix library
 ```/* * Copyright 2011, Vladimir Kostyukov * * This file is part of la4j project (http://la4j.googlecode.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package la4j.linear; import la4j.err.LinearSystemException; import la4j.factory.Factory; import la4j.matrix.Matrix; import la4j.vector.Vector; public class JacobiSolver implements LinearSystemSolver { private final static int MAX_ITERATIONS = 100000; @Override public Vector solve(LinearSystem linearSystem, Factory factory) throws LinearSystemException { Matrix a = linearSystem.coefficientsMatrix().clone(); Vector b = linearSystem.rightHandVector(); if (!isMethodCanBeUsed(a)) throw new LinearSystemException("method Jacobi can not be used"); for (int i = 0; i < a.rows(); i++) { for (int j = 0; j < a.columns(); j++) { if (i != j) a.set(i, j, a.get(i, j) / a.get(i, i)); } } int iteration = 0; Vector current = factory.createVector(linearSystem.variables()); while (iteration < MAX_ITERATIONS && !linearSystem.isSolution(current)) { Vector next = current.blank(); for (int i = 0; i < a.rows(); i++) { double sum = b.get(i) / a.get(i, i); for (int j = 0; j < a.columns(); j++) { if (i != j) sum -= a.get(i, i) * current.get(j); } next.set(i, sum); } current = next; iteration++; } if (iteration == MAX_ITERATIONS) { throw new LinearSystemException("method Jacobi can not be used"); } return current; } private boolean isMethodCanBeUsed(Matrix matrix) { for (int i = 0; i < matrix.rows(); i++) { double sum = 0; for (int j = 0; j < matrix.columns(); j++) { if (i != j) sum += Math.abs(matrix.get(i, j)); } if (sum > Math.abs(matrix.get(i, i)) - EPS) return false; } return true; } } ```

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.