Yeah I posted this last night just before I went to bed and within about a minute I had already convinced myself that nan really was the most correct way to handle it.
In the particular case in question the nan originally arose from performing a subtraction of
+inf - +inf, but in any case that you've got nan it means that the number is indeterminate, could be
–inf could be
+inf or anything in between. So it makes perfect sense that
+inf – nan = nan, since the nan on the LHS is completely indeterminate and thus could correspond to +inf.
I like Serena said:
Which math package does that?
Hi ILS. The software is gnu-Octave (a MATLAB clone). The problem arose from differences in the Matlab implementation versus the Octave implementation of some fairly simple code that was repetitively squaring a complex number until its magnitude exceeded some constant. The code didn’t check for overflows and it was causing a bug where very large complex numbers seemed to be returning an absolute value less than 2.0. It's an interesting problem because with real numbers the FP implementation of +inf and –inf usually allows this type of overflow to be handled fairly gracefully, but as this problem demonstrated, no so with complex numbers.
Take some simple code that repeats
z = z^2 to demonstrate the problem. If the starting z is complex then eventually you'll end up with something like
z = inf + j inf (here "j" is the Engineers sqrt(-1) btw).
Square it again and it's going to be trying to do something like
(inf^2 – inf^2) + j(2 inf^2), which both Matab and Octave correctly return as
z = nan + j inf. At this point there's no problem and
abs(z) returns
inf for each of the software.
Square it one more time however and it’s trying to do something like
(nan^2 – inf^2) + j(2* nan * inf). Matlab returns
nan + j nan for this while Octave returns
–inf + j nan. If you keep going like this obviously the Matlab result will just stay at
nan+j nan whereas the octave scheme will always keep an
inf for the real component (+inf after the next iteration).
The upshot is that although the Matlab way of handling it is more correct it has the unfortunate side effect that these very large complex numbers start to
fail the test
abs(z) > 2.0 because
nan returns false in all comparisons.