Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the square root of -Infinity +Infinity in Java? [duplicate]

I tried two different ways to find the square root in Java:

Math.sqrt(Double.NEGATIVE_INFINITY); // NaN
Math.pow(Double.NEGATIVE_INFINITY, 0.5); // Infinity

Why doesn't the second way return the expected answer which is NaN (same as with the first way)?

like image 809
Pratik Avatar asked Dec 29 '17 09:12

Pratik


2 Answers

A NaN is returned (under IEEE 754) in order to continue a computation when a truly undefined (intermediate) result has been obtained. An infinity is returned in order to continue a computation after an overflow has occurred.

Thus the behaviour

Math.sqrt(Double.NEGATIVE_INFINITY); // NaN

is specified because it is known (easily and quickly) that an undefined value has been generated; based solely on the sign of the argument.

However evaluation of the expression

Math.pow(Double.NEGATIVE_INFINITY, 0.5); // Infinity

encounters both an overflow AND an invalid operation. However the invalid operation recognition is critically dependent on how accurate the determination of the second argument is. If the second argument is the result of a prior rounding operation, then it may not be exactly 0.5. Thus the less serious determination, recognition of an overflow, is returned in order to avoid critical dependence of the result on the accuracy of the second argument.

Additional details on some of the reasoning behind the IEEE 754 standard, including the reasoning behind returning flag values instead of generating exceptions, is available in

What Every Computer Scientist Should Know About Floating-Point Arithmetic (1991, David Goldberg),

which is Appendix D of

Sun Microsystems Numerical Computation Guide.

like image 166
Pieter Geerkens Avatar answered Nov 20 '22 12:11

Pieter Geerkens


It is just acting as is described in the documentation of Math.

For Math.sqrt:

If the argument is NaN or less than zero, then the result is NaN.

For Math.pow:

If

  • the first argument is negative zero and the second argument is less than zero but not a finite odd integer, or
  • the first argument is negative infinity and the second argument is greater than zero but not a finite odd integer,

then the result is positive infinity.

As to why they made that design choice - you'll have to ask the authors of java.

like image 30
piet.t Avatar answered Nov 20 '22 12:11

piet.t