I understood why Math.pow(a, b)
is NaN when a
is a negative number and b
is a non-integer in JavaScript. Same is happening in other programming languages.
But, what about C++?
While in JavaScript Math.pow(-4, -2.1)
returns NaN
, in C++ pow (-4, -2.1)
returns -nan
. Why?
Example:
#include <iostream>
#include <math.h>
using namespace std;
int main () {
cout << "(4) ^ (2.1) = " << pow (4, -2.1) << endl; // 0.0544094
cout << "(-4) ^ (-2.1) = " << pow (-4, -2.1) << endl; // -nan
cout << "(-4) ^ (2.1) = " << pow (-4, 2.1) << endl; // -nan
return 0;
}
Output:
(4) ^ (2.1) = 0.0544094
(-4) ^ (-2.1) = -nan
(-4) ^ (2.1) = -nan
I compiled the code using g++
.
$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Tried that to compile it using online tools but same result is shown: