gpt4 book ai didi

java - Java 矩阵乘法

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:00 24 4
gpt4 key购买 nike

我在乘以这段代码的矩阵时遇到了一些问题,当我手动使用计算工具进行乘法时,我得到的结果与我的代码给出的完全不同。

代码:

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 因为您在其条目上使用 += 。您现在的做法无法得出正确的结果。

关于java - Java 矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28202865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com