[FEAT] Matrix Add invertible method
This commit is contained in:
@@ -203,7 +203,17 @@ bool Matrix::transpose(void)
|
||||
|
||||
double Matrix::determinant(void)
|
||||
{
|
||||
return (m_data[0][0] * m_data[1][1]) - (m_data[0][1] * m_data[1][0]);
|
||||
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]);
|
||||
|
||||
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 the_identity = {
|
||||
|
||||
@@ -65,6 +65,8 @@ namespace Raytracer
|
||||
double minor(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);
|
||||
|
||||
private:
|
||||
|
||||
@@ -332,9 +332,10 @@ TEST_CASE("[Matrix] Calculating the determinant of a 3x3 matrix", "[Matrix]")
|
||||
TEST_CASE("[Matrix] Calculating the determinant of a 4x4 matrix", "[Matrix]")
|
||||
{
|
||||
Matrix a = {
|
||||
{-2, -8, 3, 5},
|
||||
{-3, 1, 7, 3},
|
||||
{-6, 7, 7, -9}
|
||||
{-2, -8, 3, 5},
|
||||
{-3, 1, 7, 3},
|
||||
{ 1, 2, -9, 6},
|
||||
{-6, 7, 7, -9}
|
||||
};
|
||||
|
||||
REQUIRE(a.cofactor(0, 0) == 690);
|
||||
@@ -343,3 +344,33 @@ TEST_CASE("[Matrix] Calculating the determinant of a 4x4 matrix", "[Matrix]")
|
||||
REQUIRE(a.cofactor(0, 3) == 51);
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user