乘法矩阵 Java
Multiplying matrices Java
我在为这段代码乘以矩阵时遇到了一些问题,当我用计算工具手动计算时,我得到的结果与我的代码给出的结果完全不同。
代码:
public class mult1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double[][] colaO = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//orginal
double[][] colaD = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//copy
double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
mult1 test = new mult1();
test.output(colaC);
test.Alg1(colaO, colaD, colaC);
test.output(colaC);
}
public void Alg1(double colaO[][], double colaD[][], double colaC[][]) {
for (int i = 0; i < colaO.length; i++) {
for (int j = 0; j < colaO.length; j++) {
for (int k = 0; k < colaO.length; k++) {
colaC[i][j] += colaO[i][k] * colaD[k][j];
}
}
}
}
public void output(double colaC[][]) {
for (int i = 0; i < colaC.length; i++) {
for (int j = 0; j < colaC.length; j++) {
System.out.printf("%.3f", colaC[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}
结果:
---original-----
0.900 0.050 0.050
0.050 0.900 0.050
0.050 0.050 0.900
---what i'm getting------
1.715 0.143 0.143
0.143 1.715 0.143
0.143 0.143 1.715
---should be-----
0.815 0.092 0.092
0.092 0.815 0.092
0.092 0.092 0.815
我不太明白我在哪里弄乱了等式
嗯,我要做的第一件事是 0 初始化 colaC
,因为您在其条目上使用 +=
。你现在的做法无法得到正确的结果。
double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
应该是
double[][] colaC = {{0,0,0},{0,0,0},{0,0,0}};//for algs
我在为这段代码乘以矩阵时遇到了一些问题,当我用计算工具手动计算时,我得到的结果与我的代码给出的结果完全不同。
代码:
public class mult1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double[][] colaO = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//orginal
double[][] colaD = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//copy
double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
mult1 test = new mult1();
test.output(colaC);
test.Alg1(colaO, colaD, colaC);
test.output(colaC);
}
public void Alg1(double colaO[][], double colaD[][], double colaC[][]) {
for (int i = 0; i < colaO.length; i++) {
for (int j = 0; j < colaO.length; j++) {
for (int k = 0; k < colaO.length; k++) {
colaC[i][j] += colaO[i][k] * colaD[k][j];
}
}
}
}
public void output(double colaC[][]) {
for (int i = 0; i < colaC.length; i++) {
for (int j = 0; j < colaC.length; j++) {
System.out.printf("%.3f", colaC[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}
结果:
---original-----
0.900 0.050 0.050
0.050 0.900 0.050
0.050 0.050 0.900
---what i'm getting------
1.715 0.143 0.143
0.143 1.715 0.143
0.143 0.143 1.715
---should be-----
0.815 0.092 0.092
0.092 0.815 0.092
0.092 0.092 0.815
我不太明白我在哪里弄乱了等式
嗯,我要做的第一件事是 0 初始化 colaC
,因为您在其条目上使用 +=
。你现在的做法无法得到正确的结果。
double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
应该是
double[][] colaC = {{0,0,0},{0,0,0},{0,0,0}};//for algs