tomstewart89 / BasicLinearAlgebra

A library for using matrices and linear algebra on Arduino
MIT License
185 stars 38 forks source link

Integer Matrices gives wrong answers #73

Closed Incorrectone closed 2 months ago

Incorrectone commented 8 months ago

Doing this on an esp32-S3-devkit but

Determinants with integer Matrix gives wrong result

#include <BasicLinearAlgebra.h>
using namespace BLA;

void setup() {
  // Beginning the Serial Port
  Serial.begin(115200);
  // Defining the matrix
  BLA::Matrix<3,3,int> A = {9, 8, 7, 6, 5, 4, 3, 2, 1};

  Serial << "A: " << A << '\n';

  int b = BLA::Determinant(A);

  Serial << "|A|: " << b << '\n';
}

void loop() {
}

Gives 96 as the output, not zero

#include <BasicLinearAlgebra.h>
using namespace BLA;

void setup() {
  // Beginning the Serial Port
  Serial.begin(115200);
  // Defining the matrix
  BLA::Matrix<3,3> A = {9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0};
  Serial << "A: " << A << '\n';

  int b = BLA::Determinant(A);

  Serial << "|A|: " << b << '\n';
}

void loop() {
}

This gives the right result of 0

insalt-glitch commented 3 months ago

The problem is that the LUDecompose does operations on the given type. In your case, this is the integer type. Consequently, the devision here: https://github.com/tomstewart89/BasicLinearAlgebra/blob/b302d92857b1d9f0af790e54f39930627c811005/impl/NotSoBasicLinearAlgebra.h#L74 will probably produce a wrong result. One potential fix could be to check for integer types and perform the determinant calculation on floats, then convert the matrix back to integers. However, in that case, I think there is no guarantee that there won't be rounding errors.