数组乘矩阵
对于这段代码,我在乘法矩阵时遇到了一些问题,当我手工操作并使用计算工具时,我得到的结果与代码给出的结果完全不同
代码:
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
我不太明白我把等式搞砸了
# 1 楼答案
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
# 2 楼答案
我要做的第一件事是0-初始化
colaC
,因为您正在对其条目使用+=
。你现在的做法不能带来正确的结果