I am doing research in electromagnetics (a branch of physics) and I deal with complex numbers in my computing tasks (I use MATLAB). Let's say $z$ is a complex number. To calculate the square of the magnitude of $z$, which is $|z|^2$, I can use two different ways that are mathematically equivalent:
- $|z|^2 = \operatorname{abs}(z)^2$
- $|z|^2 = zz^*$
However, the outcomes of the two operations above are slightly different (numerically). The difference is usually in the last decimal point of the result, so practically this does not affect my computations. But I'm curious why this difference occurs. Now, the interesting thing is the following. I can also calculate $|z|^2$ as
- $|z|^2 = \operatorname{real}(z)^2+\operatorname{imag}(z)^2$
and this computation equals the result of $|z|^2 = zz^*$. So, how is the absolute value function (abs) implemented (in MATLAB or elsewhere)? Why does it give a different result? Which one of the results is more accurate?
x
is reallyx*(1+e)
, then squaring it exactly gives youx^2 *(1 + 2*e+ e^2)
, i.e. the relative error (neglecting the e^2) is twice as large as that in the input. Plus the rounding error in the multiply itself, which is what you are discussing here. So, this difference between two ways of finding the mag-squared is still likely less than your+2*e
term. $\endgroup$