Skip to content

Error in matrix inverse() #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jasonGranholt opened this issue Aug 31, 2022 · 5 comments
Closed

Error in matrix inverse() #3

jasonGranholt opened this issue Aug 31, 2022 · 5 comments

Comments

@jasonGranholt
Copy link

jasonGranholt commented Aug 31, 2022

Hi, found a sign error in the matrix inverse, that the tests (only 1 inverse() test) did not catch. See inverse code below with the new fix added:

    inverse() {
        if (this.rows !== this.columns) throw new Error("The matrix isn't squared!");
        const det = this.determinant();
        if (det === 0) throw new Error("Determinant is 0, can't compute inverse.");

        // Get cofactor matrix
        let sign = -1;
        const cofactor = new Matrix (this.rows, this.columns,
            this.values.map((row, i) => row.map((val, j) => {
                sign = Math.pow(-1,i+j);           /////////////////////////////////// FIXED THIS LINE ////////////////
                return sign * this.getCofactor(i, j).determinant();
            })));
        // Transpose it
        const transposedCofactor = cofactor.transpose();
        // Compute inverse of transposed / determinant on each value
        return new Matrix(this.rows, this.columns,
            this.values.map((row, i) => row.map((val, j) => transposedCofactor.at(i, j) / det)));
    }
@Kapcash
Copy link
Owner

Kapcash commented Sep 27, 2022

Feel free to open a Pull Request with your fix directly! So you could be the author of the fix commit ;)

Otherwise I'll review the change a soon as I have bandwith and fix this. Thanks you very much!

@Kapcash
Copy link
Owner

Kapcash commented Oct 16, 2022

Thanks again for spotting the error, it's very appreciated!
The method wasn't tested enough indeed. It now tests on different matrix sizes (4 & 5).

I shipped the fix with version v1.2.0. :)

@Kapcash Kapcash closed this as completed Oct 16, 2022
@jasonGranholt
Copy link
Author

Hi, the npm package for 1.2.0 does not have the inverse() fix, the compiled file in dist/ts-matrix.mjs still use the old code.

Could you check this? Thanks, Jason

@Kapcash
Copy link
Owner

Kapcash commented Nov 7, 2022

You're right! I must have publish an old build dist/ by mistake 😅

Can you check with versions 1.2.1 or 1.2.2? They now includes sourcemaps and the src/ folder directly in the package so people can debug and take a look directly when installing :)

@jasonGranholt
Copy link
Author

Thanks, it works now😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants