I have the next code, which multiplies the probability matrix p
the certain number of times. For the first 50 iterations everything is ok, the sum of probabilities in each row is equal to 1
, but then I recieve the sum > 1
and approximately on the 70th iteration I recieve infinity values. And I do not understand why.
The sum
of probabilities in each row must be equal to 1
. This is the classic Markov's chain model. And regardless of num of multiplications you must receive the sum = 1
in each row. I suppose there is a problem in a floating-point calculation.
public class Test {
public static void main(String[] args) {
int trials = Integer.parseInt(args[0]);
double[][] p = {
{0.02, 0.92, 0.02, 0.02, 0.02},
{0.02, 0.02, 0.38, 0.38, 0.2},
{0.02, 0.02, 0.02, 0.92, 0.02},
{0.92, 0.02, 0.02, 0.02, 0.02},
{0.47, 0.02, 0.47, 0.02, 0.02}};
for (int t = 0; t < trials; t++) {
p = multiply(p, p);
}
for (int i = 0; i < p.length; i++) {
for (int j = 0; j < p[i].length; j++) {
System.out.printf("%9.4f", p[i][j]);
}
System.out.println();
}
}
public static double[][] multiply(double[][] a, double[][] b) {
int w = a[0].length;
int l = b.length;
if (w != l) {
throw new IllegalArgumentException("The number of columns " +
"in the first matrix must be equal to the number " +
"of rows in second matrix!" + w + " " + l);
}
double[][] result = new double[a.length][b[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b[0].length; j++) {
for (int k = 0; k < b.length; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}
}
/*
output for the trials = 30:
0,2730 0,2657 0,1462 0,2472 0,0678
0,2730 0,2657 0,1462 0,2472 0,0678
0,2730 0,2657 0,1462 0,2472 0,0678
0,2730 0,2657 0,1462 0,2472 0,0678
0,2730 0,2657 0,1462 0,2472 0,0678
output for the trials = 45:
0,2732 0,2659 0,1463 0,2474 0,0679
0,2732 0,2659 0,1463 0,2474 0,0679
0,2732 0,2659 0,1463 0,2474 0,0679
0,2732 0,2659 0,1463 0,2474 0,0679
0,2732 0,2659 0,1463 0,2474 0,0679
output for the trials = 55:
0,5183 0,5044 0,2775 0,4693 0,1288
0,5183 0,5044 0,2775 0,4693 0,1288
0,5183 0,5044 0,2775 0,4693 0,1288
0,5183 0,5044 0,2775 0,4693 0,1288
0,5183 0,5044 0,2775 0,4693 0,1288
output for the trials = 70:
Infinity Infinity Infinity Infinity Infinity
Infinity Infinity Infinity Infinity Infinity
Infinity Infinity Infinity Infinity Infinity
Infinity Infinity Infinity Infinity Infinity
Infinity Infinity Infinity Infinity Infinity
*/