2

I am new to Java. I am writing a small program to calculate the value of a number raised to a power, when I ran into a problem with negative numbers raised to a fractional exponent.

System.out.println(Math.pow(-8, 1/3f));

The output is NaN while I'm expecting -2?

What am I doing wrong? Are there any alternatives to calculate problems like this?

Any help appreciated.

christopher_pk
  • 641
  • 4
  • 17
  • This gets a Complex number. Hence It gives NaN. Read [This Question](http://stackoverflow.com/questions/20250453/why-math-powa-b-is-nan-when-a-is-a-negative-number-and-b-is-a-non-integer) – ThisaruG Feb 10 '16 at 10:19
  • I am expecting (-2)^3=-8, so answer is -2? – christopher_pk Feb 10 '16 at 10:20
  • 1
    In this case it could return a real number that would be correct, but in general the result space for `(-n)^(1/m)` would be some set of complex numbers, so the spec says that it should consistently just return NaN. – khelwood Feb 10 '16 at 10:22
  • how can I get a real value if possible? – christopher_pk Feb 10 '16 at 10:23
  • 1
    Depends what you are actually trying to do. If it is to find out the cube root of `-8`, just assign `-2`. If it is to find out the cube root of _any_ negative number, then you can negate the cube root of the positive number. If it is to find any power of two numbers, you may be out of luck. – khelwood Feb 10 '16 at 10:25
  • thanks khelwood. I am trying to get result for any two numbers, but guess there is no other way. I understand now, thanks a lot. – christopher_pk Feb 10 '16 at 10:27
  • 1
    Actually `1/3f` is not 1/3, just a very close number to it, so it cannot be used that way. – Gábor Bakos Feb 10 '16 at 10:28

1 Answers1

2

This case is described in documentation .

If the first argument is finite and less than zero. <...> if the second argument is finite and not an integer, then the result is NaN.

As far as I know there is no method in Java standard library to do it, so you have to implement it manually.

Kuvaldis
  • 348
  • 1
  • 9