Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When the result of the operations involving Double or Float data types in Java produces some unpredicatable output, it is designated by NaN (Not a Number).

Why does the statement that uses Math.pow() produce NaN?

Java
System.out.println(Math.pow(-0.9, 0.8));


Of course, it may be easy for you, I can't figure it out, please.
Posted

That's how it works. Here, read at the details: Java.lang.Math.pow() Method[^]

If the first argument is finite and less than zero:
- if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument
- if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument
- if the second argument is finite and not an integer, then the result is NaN.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 24-Oct-12 17:30pm    
Of course (my 5), but needs mathematical explanation. Why is it so? This is what OP really misses.
Please see my answer.
--SA
Have you ever heard of complex number? In not complex number, have you ever heard that, in real numbers, square root of negative number cannot be found; in other words, the equation x² = −1 has no solutions in read numbers?! And, of course, the same stands for 0.8 and −0.9.

This is something like middle school… and such school should be a prerequisite for starting with computing.

And NaN means "not a number", important object reserved to IEEE 754 floating number representation to represent the concept of invalid number. Please see:
http://en.wikipedia.org/wiki/IEEE_754[^].

(Sigh…)

—SA
 
Share this answer
 
v5
I'm guessing it's because the result is complex, according to WolframAlpha[^], and the float/double type isn't able to represent it.
 
Share this answer
 
For understanding it you should know that:
  1. (Math) The result of power operation might be a complex number (when base is negative and exponent is not integer).
  2. (Computing) pow returns a double. Such datatype cannot represent a complex number (technically it 'approximates' a real number).

Reading the pow method documentation[^] would help too.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900