Boostr



0 votes
31 views
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)?
asked Dec 30, 2017 in Core java by Amrendra | 31 views



2 Answers

0 votes
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
answered Dec 30, 2017 by Amrendra
0 votes
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.
answered Dec 30, 2017 by Amrendra

Related Questions



Welcome to Knowledge Boostr, where you can ask questions and receive answers from other members of the community.
This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers


23,494 questions
40,169 answers
12 comments
23,610 users