c - Arduino线性方程求解器,打印错误答案

标签 c matrix arduino calculator linear-algebra

请帮助我,我们将不胜感激。 我用 C 编写了一个代码来解方程,但我不知道为什么我输入到这个计算器中的一些方程给了我错误的值,该算法是正确的,因为我在 C 中执行它并给出了正确的答案,但是当我在arduino上使用它有时它不会给我正确的答案,这是完整的代码

如有任何帮助,我们将不胜感激。

.
.
.
.

.
.
.
long jordan(){/*this do the gauss elimination for solve the equation*/
long FilaMax=0,k=0;
long double maxEl=0,tmp=0,fracc=0;
   lcd.clear();
for (colum=0; colum<cant-1; colum++) {
    /* search the maximun colum*/
    maxEl = abs(a[colum][colum]);
    FilaMax = colum;
    for (k=colum+1; k<cant; k++) {
        if (abs(a[k][colum]) > maxEl) {
            maxEl = abs(a[k][colum]);
            FilaMax = k;
        }
    }
    /* change the maximunby the actual row*/
    for (k=colum; k<cant+1;k++) {
        tmp = a[FilaMax][k];
        a[FilaMax][k] = a[colum][k];
        a[colum][k] = tmp;
    }
    /*lower cero's triangular matrix it's done here*/
    for (k=colum+1;k<cant; k++) {
        fracc = -a[k][colum]/a[colum][colum];
        for (fila=colum; fila<cant+1; fila++) {
            if (colum==fila) {
                a[k][fila] = 0;
            }else{
                a[k][fila] += fracc * a[colum][fila];
            }
        }
             } 
}
    char sr=' ';
    lcd.setCursor(0,0);
if(a[cant-1][cant-1]==0){
    lcd.print("No solucion"); /* if there is no solution print this*/ 
    do{
    sr=keypad.waitForKey();
    }while(sr!='\n');
}else{                       /*is there values to print*/
for (colum=cant-1; colum>=0; colum--) {
    res[colum] = a[colum][cant]/a[colum][colum];
    for (k=colum-1;k>=0;k--) {
        a[k][cant] -= a[k][colum]*res[colum];
    }
}
colum=0;
    do{     
            lcd.setCursor(0,0);
            lcd.print("R");
            lcd.setCursor(1,0);
            lcd.print(colum+1);
            lcd.setCursor(0,1);
    lcd.print(res[colum],DEC);
            sr=keypad.waitForKey();
            if(sr=='#') colum++;
            if (colum==cant) colum=0;
            if(sr=='\n') break;
    }while(1);
   }
   colum=0;
   fila=0;
   cant=0;
   sr=' ';
  return 0;
 }

尝试使用以下代码:

 input:
    # size
    4
    elements:
    1 -2 1 1 2
    3 0 2 -2 -8
    0 4 -1 -1 1
    5 0 3 -1 -3 
 output:
 some numbers

 it should print without solution.

我首先在电脑上运行c中的代码,算法工作完美,但是当我复制到arduino时,它在大多数情况下无法按预期工作,为线性系统提供正确的答案,但有时会失败

任何帮助将不胜感激。

最佳答案

这是一个浮点错误,您得到的最终值非常接近于零。 Demo .

在最终测试中添加一个小的 epsilon 值以允许浮点不准确:

if(fabs(a[cant-1][cant-1]) < 0.000001){
    lcd.print("No solucion"); /* if there is no solution print this*/

关于c - Arduino线性方程求解器,打印错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30793805/

相关文章:

c - "new"关键字在 ANSI C 中意味着什么?

Python——计算共现矩阵

c - 如何连接数字字符串然后将其分配给 'long' 类型变量?

algorithm - M2(R) 中的多项式乘法?

c++ - xcode,带有arduino的c++串口

java - 有没有所谓的自运行应用程序?

c - 如何在 AVX 或 SSE 指令中进行间接加载(聚集-分散)?

Python:GUI - 绘图,从实时 GUI 中的像素读取

c++ - 结构和函数 - 不命名类型

c - 将 uint8_t 中的位地址作为结构体的成员