【发布时间】:2021-06-02 09:26:13
【问题描述】:
我有下一个代码,它将 概率矩阵 p 乘以一定的次数。对于前 50 次迭代,一切正常,每行中的概率总和等于 1,但随后我收到 sum > 1,大约在第 70 次迭代时,我收到无穷大值。我不明白为什么。
每行中概率的sum 必须等于1。这是经典的马尔可夫链模型。无论乘法的数量如何,您都必须在每一行中收到sum = 1。我想浮点计算有问题。
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
*/
【问题讨论】:
标签: java arrays matrix precision matrix-multiplication