When using pow()
from cmath library I get NaN but if I iterate for the length of the power, it works?
I am trying to evaluate y=0.05*(1+-2.01655)^x
where 90 < x < 180
and I am receiving NaN when using pow((1+-2.01655),x)
but iterating in a for loop achieves the correct answer? Worth noting excel also exhibits a similar issue (cannot evaluate raw form but can evaluate a segmented form).
double var = -1.01655;
double final = 1;
for(int i=0 ; i<ceil(x); i++){
final *= var;
}
final = 0.05 * final;
Taking a fractional exponent of a number implies an nth-root operation; for example pow(2, 3.0 / 2.0) == sqrt(pow(2, 3))
.
Negative numbers often have imaginary roots. std::pow
for doubles only handles reals. 1 - 2.01655
is, of course, negative, so your equation only has real results for integer values of x. I think you'll find that integer values of x generate a result and non-integer values are generating NaN. The reason your loop works is that you're calculating an integer power, not a fractional power.
See cppreference; the section on error handling:
If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur.