In numerical recipes in C, absolute value of complex number $a+ib$ is implemented as $b*\sqrt{1+\left(\frac{a}{b}\right)^2}$ if $|b|$ is greater than $|a|$ and $a*\sqrt{1+\left(\frac{b}{a}\right)^2}$ if $|a|$ is greater than $|b|$. Does the numerical error in the absolute value calculation reduce when doing this. If so, how?
-
If fact, the condition are $|a|\lt |b|$ and $|a| \geq |b|$ – Claude Leibovici Apr 12 '14 at 13:38
-
Thanks Claude. That is right. I will edit my post. – Discretizer Apr 12 '14 at 17:44
2 Answers
One point in favor of these formulas is that if you just do $\sqrt{a^2+b^2}$ there's a risk of overflow or underflow when you square the $a$ and $b$. The NR formulas will avoid this right up (or down) to the limit of the floating-point representation.
- 286,031
That is a very strange way of defining the 'absolute value of a complex number' (should be called the modulus of the complex number).
Really, you don't need those conditions. Even if you used the 'wrong' formula, you will still get the exact same answers. In fact, the given formulas introduce conditions about $a$ and $b$ being non-zero, which is most certainly unnecessary (since the modulus can still be computed even if either $a$ or $b$ are zero).
Also, I don't understand what you mean by the 'numerical error' of the modulus. There is no numerical error, the modulus is not an approximation. It gives an exact value.
- 10,331
-
1Note that the question is tagged "numerical methods" and mentions Numerical Recipes -- so the matter is not exact mathematics, but practical computation with limited-precision floating-point numbers. In that context there certainly are numerical errors. That's what makes it hard! – hmakholm left over Monica Apr 12 '14 at 13:08
-
Perhaps this is a field that I am unfamiliar with, in which case please ignore my response. I was under the impression that Discretizer was somebody who wanted to learn how to compute the modulus of a complex number, in which case I found the formulas to be highly impractical! – Trogdor Apr 12 '14 at 13:10
-
1x @Trogdor: The point is that he wants to compute the modulus on a computer. It is common for the default floating-point datatype only to be able to represent numbers less than $2^{1024}$, so if you try to compute $|2^{600}+42i|$ using the naive algorithm, the square of $2^{600}$ will overflow to infinity, and you get a result of "infinity" instead $2^{600}$ (which would be the representable number closest to the true result). – hmakholm left over Monica Apr 12 '14 at 13:22
-
Very interesting, you learn something new every day. Cheers for filling me in, I can now see the advantage of the provided form. – Trogdor Apr 12 '14 at 13:26