[英]I am trying to add vectors in a for loop, but after 2 iterations I get an incorrect answer (C)
I am trying to implement the iterative formula Xn+1 = T*Xn + C, for a given number of iterations i.对于给定的迭代次数 i,我正在尝试实现迭代公式 Xn+1 = T*Xn + C。 Here X and C are vectors and T is a 3x3 matrix.
这里 X 和 C 是向量,T 是一个 3x3 矩阵。 However, if I go beyond 2 iterations (fori=0;i<2;i++) the formula starts giving an incorrect result and I am not sure why.
但是,如果我超过 2 次迭代 (fori=0;i<2;i++),公式开始给出不正确的结果,我不知道为什么。 Any help is appreciated.
任何帮助表示赞赏。
#include <stdio.h>
int main(void) {
double T[3][3] = {{0.0,-0.5,-0.75},
{0.6,0.0,0.4},
{0.25,-0.375,0.0}};
double C[3] = {2.0,2.8,3.375};
double x_n[3] = {0.0,0.0,0.0};
double x_n_plus_1[3] = {0.0,0.0,0.0};
double Tx[3] = {0.0,0.0,0.0};
int i, row, col, ctr;
for(i=0;i<3;i++) {
for(row=0;row<3;row++) {
for(col=0;col<3;col++){
Tx[row] += T[row][col] * x_n[col]; //Tx_n = T*x_n
}
}
for(ctr=0;ctr<3;ctr++) {
x_n_plus_1[ctr] = Tx[ctr] + C[ctr];//x_n+1 = Tx_n + C
}
for(ctr=0;ctr<3;ctr++) {
x_n[ctr] = x_n_plus_1[ctr];
}
}
for(ctr=0;ctr<3;ctr++) {
printf("%lf\n",x_n[ctr]);
}
return 0;
}
As pmg
proposed: "You need to reset the elements of Tx to zero at the beginning (or end) of each i loop".正如
pmg
建议的那样:“您需要在每个 i 循环的开始(或结束)将 Tx 的元素重置为零”。 For each iteration of i, you need to re-initialize the Tx.对于 i 的每次迭代,您都需要重新初始化 Tx。 If you go beyond 2 iterations (fori=0;i<2;i++) the formula starts giving an incorrect result because, staring second iteration, Tx is not still equal to {0, 0, 0}
如果超过 2 次迭代 (fori=0;i<2;i++),则公式开始给出错误结果,因为在第二次迭代时,Tx 仍不等于 {0, 0, 0}
#include <stdio.h>
int main(void) {
double T[3][3] = {{0.0,-0.5,-0.75},
{0.6,0.0,0.4},
{0.25,-0.375,0.0}};
double C[3] = {2.0,2.8,3.375};
double x_n[3] = {0.0,0.0,0.0};
double x_n_plus_1[3] = {0.0,0.0,0.0};
int i, row, col, ctr;
for(i=0;i<3;i++) {
double Tx[3] = {0.0, 0.0, 0.0};
for(row=0;row<3;row++) {
for(col=0;col<3;col++){
Tx[row] += T[row][col] * x_n[col]; //Tx_n = T*x_n
}
}
for(ctr=0;ctr<3;ctr++) {
x_n_plus_1[ctr] = Tx[ctr] + C[ctr];//x_n+1 = Tx_n + C
}
for(ctr=0;ctr<3;ctr++) {
x_n[ctr] = x_n_plus_1[ctr];
}
}
for(ctr=0;ctr<3;ctr++) {
printf("%lf\n",x_n[ctr]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.