Looking at the c++ standard [1] we are missing this function:

norm() = a^2 + b^2

The field norm of the complex, or the square of the absolute. An example on C++ 
reference states that this is faster for comparing magnitudes for ranking as it 
avoids the sqrt() required in abs().

z.abs() > y.abs()  ==  z.norm() > y.norm()


I suggest this is added to comply with the standard.


It seems odd to me that the constructor ofPolar throws an exception. It does 
this when the magnitude (rho) for the complex is negative. However if the 
magnitude is NaN it will not throw an exception and will end up returning NaN. 
I think this should be changed to return NaN for negative magnitude and avoid 
exceptions. This is basically stating that the polar representation you used is 
invalid and so in the Cartesian representation it will be (nan, nan).

The C++ standard on this was previously vague and was clarified in [2]:

“
-?- Requires: rho shall be non-negative and non-NaN. theta shall be finite.

-9- Returns: The complex value corresponding to a complex number whose 
magnitude is rho and whose phase angle is theta.
“

The assumption is that abs(polar(rho, theta)) == rho.

If this cannot be ensured then polar(rho, theta) is undefined and we return NaN.


Note that if theta is finite and rho is non-negative and non-nan:

x = rho * Math.cos(theta)
y = rho * Math.sin(theta)

In the event that sin(theta) is zero (i.e. theta is zero) then inf * 0 is NaN. 
In this case the complex could either be:

(Inf, nan) or (inf, 0)

I have tried 2 c++ implementations and both return (inf, nan). The c++ 
<complex> header I have found would return (inf, 0). The same header also 
corrects if cos(theta) is zero however in Java cos(pi/2) is not zero so this is 
not an issue.

Note:
If the result is (inf, nan) then abs((inf, nan)) should return inf to satisfy 
the contract abs(polar(rho, theta)) == rho. This is currently true as abs() 
uses Math.hypot(x, y) which will return positive infinity if either argument is 
infinite. So I do not think it matters. An infinite is infinite even when the 
other part is nan.


I suggest we update ofPolar to not throw exceptions and return NAN unless theta 
is finite and rho is non-negative and non-nan.

Alex


[1] http://www.cplusplus.com/reference/complex/ 
<http://www.cplusplus.com/reference/complex/>
[2] https://cplusplus.github.io/LWG/issue2459 
<https://cplusplus.github.io/LWG/issue2459>


Reply via email to