I observed a simple, yet particular behavior when using the determinant function in MATLAB and I would like to get some explanations as I didn't find anything about it in the function help documentation.
I'm generating a random unitary matrix Q
with the following code:
[Q, R] = qr(randn(3));
After that, I evaluate the determinant of Q with the det
function:
det(Q)
I would expect the result to be -1.000
or 1.000
. However, the format doesn't seem to be constant. So when I do something like this:
detResults = zeros(100,1);
for ii = 1:100
[Q, R] = qr(randn(3));
detResults(ii,1) = det(Q);
end
the detResults
vector contains 1.000
and sometime 1
. Is it just a print format issue or is it caused by something else?
It's related to floating-point precision. Each time you iterate through that loop, even though you will theoretically get a determinant of 1 for the
Q
matrix, the numbers in the matrices themselves are irrational so theoretically the only way you will get the value of 1 is when your numbers are represented with infinite precision. Sometimes there are enough digits so that MATLAB can safely round to 1 with assurance. Also, you're not getting the full picture. The reason why you see1.0000
and1
is also related to the print format. The default print format only shows up to five decimal places but it may be prudent to show more decimal places to appreciate the bigger picture.Here's a small example with using only 10 iterations instead of 100.
Using the default print format:
Using a format of increased precision (just for display purposes) with
format long g
:Internally, it really depends on what the
Q
matrix is and what you get out of the bag when you generate the random matrices. However, as far as precision goes for using these for further calculations,0.999...
is very close to 1 so for all intents and purposes you should consider it equal to 1.