I had an error. I need to create a stochastic matrix, for example:

input: 0.1 0.9 0.0 // 0.1 + 0.9 + 0.0 = 1 0.5 0.4 0.1 0.3 0.4 0.3 

The matrix is ​​stochastic, because when counting rows there will be 1

My program works through time.

My code:

 public class maticeStochaticka { private static Scanner sc = new Scanner(System.in); public static boolean pocetStochastic(double rozmerMatici[][]) { for (int i = 0; i < rozmerMatici.length; i++) { double sum = 0; for (int j = 0; j < rozmerMatici[i].length; j++) sum = sum + rozmerMatici[i][j]; if (sum != 1) return false; } return true; } public static void main(String[] args) { System.out.println("Задайте размер матрицы: "); int rozmerMaticiAlfa = sc.nextInt(); double [][] rozmerMatici = new double[rozmerMaticiAlfa][rozmerMaticiAlfa]; System.out.println("Задайте матрицу "); for (int i = 0; i < rozmerMaticiAlfa; i++) { for (int j = 0; j < rozmerMaticiAlfa; j++) { rozmerMatici[i][j] = sc.nextFloat(); } } if (pocetStochastic(rozmerMatici)) { System.out.println("матрица стохастическая"); } else { System.out.println("матрица не стохастическая"); } } } 

Please help.

    1 answer 1

    double has errors in operations, so it is better to compare it not using the comparison operator "==", but through checking the difference value.

     public static boolean pocetStochastic(double rozmerMatici[][]) { for (int i = 0; i < rozmerMatici.length; i++) { double sum = 0; for (int j = 0; j < rozmerMatici[i].length; j++) sum = sum + rozmerMatici[i][j]; if (Math.abs(sum - 1.0d) > 0.00001d) return false; } return true; 

    }