[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.