[FEAT] Matrix Add invertible method

This commit is contained in:
NADAL Jean-Baptiste
2024-02-05 10:05:31 +01:00
parent ef0bb1a6e2
commit 8461c3da6b
3 changed files with 57 additions and 4 deletions

View File

@@ -203,7 +203,17 @@ bool Matrix::transpose(void)
double Matrix::determinant(void) double Matrix::determinant(void)
{ {
double the_det = 0;
if (m_rows == 2)
return (m_data[0][0] * m_data[1][1]) - (m_data[0][1] * m_data[1][0]); return (m_data[0][0] * m_data[1][1]) - (m_data[0][1] * m_data[1][0]);
for (int the_col = 0; the_col < m_cols; the_col++)
{
the_det += m_data[0][the_col] * cofactor(0, the_col);
}
return the_det;
} }
/* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */
@@ -247,6 +257,16 @@ double Matrix::cofactor(uint8_t a_row, uint8_t a_col)
/* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */
bool Matrix::invertible(void)
{
if (determinant() == 0)
return false;
return true;
}
/* ------------------------------------------------------------------------- */
Matrix Matrix::identity(void) Matrix Matrix::identity(void)
{ {
Matrix the_identity = { Matrix the_identity = {

View File

@@ -65,6 +65,8 @@ namespace Raytracer
double minor(uint8_t a_row, uint8_t a_col); double minor(uint8_t a_row, uint8_t a_col);
double cofactor(uint8_t a_row, uint8_t a_col); double cofactor(uint8_t a_row, uint8_t a_col);
bool invertible(void);
static Matrix identity(void); static Matrix identity(void);
private: private:

View File

@@ -334,6 +334,7 @@ TEST_CASE("[Matrix] Calculating the determinant of a 4x4 matrix", "[Matrix]")
Matrix a = { Matrix a = {
{-2, -8, 3, 5}, {-2, -8, 3, 5},
{-3, 1, 7, 3}, {-3, 1, 7, 3},
{ 1, 2, -9, 6},
{-6, 7, 7, -9} {-6, 7, 7, -9}
}; };
@@ -343,3 +344,33 @@ TEST_CASE("[Matrix] Calculating the determinant of a 4x4 matrix", "[Matrix]")
REQUIRE(a.cofactor(0, 3) == 51); REQUIRE(a.cofactor(0, 3) == 51);
REQUIRE(a.determinant() == -4071); REQUIRE(a.determinant() == -4071);
} }
/* ------------------------------------------------------------------------- */
TEST_CASE("[Matrix] Testing an invertible matrix for invertibility", "[Matrix]")
{
Matrix a = {
{6, 4, 4, 4},
{5, 5, 7, 6},
{4, -9, 3, -7},
{9, 1, 7, -6}
};
REQUIRE(a.determinant() == -2120);
REQUIRE(a.invertible() == true);
}
/* ------------------------------------------------------------------------- */
TEST_CASE("[Matrix] Testing an noninvertible matrix for invertibility", "[Matrix]")
{
Matrix a = {
{-4, 2, -2, -3},
{ 9, 6, 2, 6},
{ 0, -5, 1, -5},
{ 0, 0, 0, 0}
};
REQUIRE(a.determinant() == 0);
REQUIRE(a.invertible() == false);
}