mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Added determinate function (#1429)
* Added determinate function * Changed determinate function name * Changed instance of .det() to .determinate() * Added force_test() function * Update tests.py
This commit is contained in:
parent
7b3d385ad6
commit
07483139d1
|
@ -45,7 +45,8 @@ This module contains some useful classes and functions for dealing with linear a
|
|||
- changeComponent(x,y,value) : changes the specified component.
|
||||
- component(x,y) : returns the specified component.
|
||||
- width() : returns the width of the matrix
|
||||
- height() : returns the height of the matrix
|
||||
- height() : returns the height of the matrix
|
||||
- determinate() : returns the determinate of the matrix if it is square
|
||||
- operator + : implements the matrix-addition.
|
||||
- operator - _ implements the matrix-subtraction
|
||||
|
||||
|
|
|
@ -277,6 +277,33 @@ class Matrix(object):
|
|||
"""
|
||||
return self.__height
|
||||
|
||||
def determinate(self) -> float:
|
||||
"""
|
||||
returns the determinate of an nxn matrix using Laplace expansion
|
||||
"""
|
||||
if self.__height == self.__width and self.__width >= 2:
|
||||
total = 0
|
||||
if self.__width > 2:
|
||||
for x in range(0, self.__width):
|
||||
for y in range(0, self.__height):
|
||||
total += (
|
||||
self.__matrix[x][y]
|
||||
* (-1) ** (x + y)
|
||||
* Matrix(
|
||||
self.__matrix[0:x] + self.__matrix[x + 1 :],
|
||||
self.__width - 1,
|
||||
self.__height - 1,
|
||||
).determinate()
|
||||
)
|
||||
else:
|
||||
return (
|
||||
self.__matrix[0][0] * self.__matrix[1][1]
|
||||
- self.__matrix[0][1] * self.__matrix[1][0]
|
||||
)
|
||||
return total
|
||||
else:
|
||||
raise Exception("matrix is not square")
|
||||
|
||||
def __mul__(self, other):
|
||||
"""
|
||||
implements the matrix-vector multiplication.
|
||||
|
|
|
@ -118,6 +118,13 @@ class Test(unittest.TestCase):
|
|||
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
|
||||
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", str(A))
|
||||
|
||||
def test_determinate(self):
|
||||
"""
|
||||
test for determinate()
|
||||
"""
|
||||
A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4)
|
||||
self.assertEqual(-376, A.determinate())
|
||||
|
||||
def test__mul__matrix(self):
|
||||
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3)
|
||||
x = Vector([1, 2, 3])
|
||||
|
@ -149,6 +156,13 @@ class Test(unittest.TestCase):
|
|||
str(squareZeroMatrix(5)),
|
||||
)
|
||||
|
||||
|
||||
def force_test() -> None:
|
||||
"""
|
||||
This will ensure that pytest runs the unit tests above.
|
||||
To explore https://github.com/TheAlgorithms/Python/pull/1124 uncomment the line below.
|
||||
>>> # unittest.main()
|
||||
"""
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
Loading…
Reference in New Issue
Block a user