7

I observed the following Javascript behavior:

> Math.pow(4, 2)
16
> Math.pow(4, 2.1)
18.37917367995256
> Math.pow(4, 0.5)
2
> Math.pow(-4, 2)
16
> Math.pow(-4, 2.1)
NaN
> Math.pow(-4, 0.5)
NaN

Why giving a negative number and a non-integer but rational number, makes Math.pow to return NaN?

For example, why Math.pow(4, 0.5) is not NaN but Math.pow(4, -0.5) is NaN?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

3 Answers3

7

Imaginary (Complex) Number Alert!

I have got a crazy result too. So what I have here is the same logic in different programming languages.

What I feel is, when the power is calculated, the resulting number is root of -1, which is an imaginary number. These programs cannot handle imaginary numbers is my guess.


The results are as follows:

C#

Math.Pow(-1.1, -1.1);    // Returns NaN

Java Output

Math.pow(-4, 2.1);      // Returns NaN

JavaScript

Math.pow(-4, 2.1);      // Returns NaN
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
5

Because you've tried to compute a number that is not real. For example no real number is the solution to -4 to the power of 0.5. And so there comes the world of IMAGINARY NUMBERS.

You will get the best answer when you will see that ECMAscript specification seems to say so.

Returns an implementation-dependent approximation to the result of raising x to the power y.

15.8.2.13 pow (x, y) # Ⓣ Ⓡ

  • If y is NaN, the result is NaN.
  • If y is +0, the result is 1, even if x is NaN.
  • If y is −0, the result is 1, even if x is NaN.
  • If x is NaN and y is nonzero, the result is NaN.
  • If abs(x)>1 and y is +∞, the result is +∞.
  • If abs(x)>1 and y is −∞, the result is +0.
  • If abs(x)==1 and y is +∞, the result is NaN.
  • If abs(x)==1 and y is −∞, the result is NaN.
  • If abs(x)<1 and y is +∞, the result is +0.
  • If abs(x)<1 and y is −∞, the result is +∞.
  • If x < 0 and x is finite and y is finite and y is not an integer, the result is NaN.

.......................

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

It's due to mathematics. Your value would be an imaginary number (complex numbers) which is not supported. :)

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49