I wanted to do some exercise and came up with the idea of a good challenge ( forfor my level ofcourse of course).
Tried I tried to implement LaPlace's algorithm for computing the determinant, recusivelyrecursively.
This is the result:
The concept is simple,: you have a matrix of order nn. While doing this by hand you'd prefer chosing a row that's particularly math friendly; since it's a computer doing the dirty work it really doesn't care about what number he's multiplying.
Every element m_IJm_IJ
of a matrix has a minor. A minor is the determinant of a matrix without the Ith row and the Jth column. With this we can define the det of a matrix like so:
Sum (-1)^i+j * a_ij * M_ij - where M_ij is the minimum of the element a_ij
once(where M_ij
is the minimum of the element a_ij
)
Once a matrix reach the order == 2 it just computes the determinant since is just a simple moltiplicationmultiplication between 4 elements.
At first iI had problems finding something that could be used as a matrix object and be passed around from one function to another.
I I tried bi-dimensional arrays, but they aren't dinamicdynamic and couldn't understand how iI could pass an array object to a function.
I I was looking for some hidden matrix type or class to use but i had no luck what so ever.
So iI came up with "a vector of vectors" which worked but i'mI'm not completely sure it's a really good idea. Not even counting that vector <vector<double> >
looks awful.
Secondly, running some recursion tracking iI found out that the time it takes ramps up so damn quickly:
- Order 3 = 4 calls
- Order 4 = 17 calls
- Order 5 = 86 calls
- ...
- Order 10 = 2.606.501 calls (holymoly)
althoughAlthough, even in the latter case, it doesn't take too much: 3 to 4 seconds.
Is Is there a way to reduce the steepness of the curve?
This This way it gets out of hand way too soon.
I don't have a huge programming experience so iI know almost nothing on optimization or good practice either.
Since i Since I have some fresh code to work with i'dI'd like to know any error iI might be doing and way to optimize this algorithm.
OT: a little ot, just my curiosity. howHow costly is to cast a type? theThe (type) x type of cast to be clear( sorry for the mouthful).
EDIT: I forgot to ask. What could be a better way to input a matrix from the user?
Cheers!