|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +/** |
| 4 | + * Utility class to check whether a matrix is stochastic. |
| 5 | + * A matrix is stochastic if all its elements are non-negative |
| 6 | + * and the sum of each row or column is equal to 1. |
| 7 | + */ |
| 8 | +public final class StochasticMatrix { |
| 9 | + |
| 10 | + private static final double TOLERANCE = 1e-9; |
| 11 | + |
| 12 | + private StochasticMatrix() { |
| 13 | + // Utility class |
| 14 | + } |
| 15 | + |
| 16 | + /** |
| 17 | + * Checks if a matrix is row-stochastic. |
| 18 | + * |
| 19 | + * @param matrix the matrix to check |
| 20 | + * @return true if the matrix is row-stochastic |
| 21 | + * @throws IllegalArgumentException if matrix is null or empty |
| 22 | + */ |
| 23 | + public static boolean isRowStochastic(double[][] matrix) { |
| 24 | + validateMatrix(matrix); |
| 25 | + |
| 26 | + for (double[] row : matrix) { |
| 27 | + double sum = 0.0; |
| 28 | + for (double value : row) { |
| 29 | + if (value < 0) { |
| 30 | + return false; |
| 31 | + } |
| 32 | + sum += value; |
| 33 | + } |
| 34 | + if (Math.abs(sum - 1.0) > TOLERANCE) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Checks if a matrix is column-stochastic. |
| 43 | + * |
| 44 | + * @param matrix the matrix to check |
| 45 | + * @return true if the matrix is column-stochastic |
| 46 | + * @throws IllegalArgumentException if matrix is null or empty |
| 47 | + */ |
| 48 | + public static boolean isColumnStochastic(double[][] matrix) { |
| 49 | + validateMatrix(matrix); |
| 50 | + |
| 51 | + int rows = matrix.length; |
| 52 | + int cols = matrix[0].length; |
| 53 | + |
| 54 | + for (int j = 0; j < cols; j++) { |
| 55 | + double sum = 0.0; |
| 56 | + for (int i = 0; i < rows; i++) { |
| 57 | + if (matrix[i][j] < 0) { |
| 58 | + return false; |
| 59 | + } |
| 60 | + sum += matrix[i][j]; |
| 61 | + } |
| 62 | + if (Math.abs(sum - 1.0) > TOLERANCE) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + } |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + private static void validateMatrix(double[][] matrix) { |
| 70 | + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { |
| 71 | + throw new IllegalArgumentException("Matrix must not be null or empty"); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments