John Smith wrote:
> In a C program I need to do exponentiation where the base is negative
> and the exponent is a fraction. In standard C this would be something
> like t = pow(-11.5, .333), but with this combination of arguments there
> is a domain error and the result is a percolating NaN.
>
> I worked around the problem by putting the standard function in a wrapper:
>
> double xpow(double b, double x)
> {
> double p;
>
> if(b < 0)
> {
> p = pow(-b, x);
> p *= -1.0;
> }
> else p = pow(b, x);
>
> return p;
> }
>
> Is there any particular reason for this limitation in the standard
> library function? Has anyone else had a problem with this and found a
> better solution?
The reason for the limitation is mathematical: The proper
result of pow(-1,1.5) is -i, where i is the square root of -1.
That imaginary value is not in the range of double, so the pow
function cannot return it.
You define xpow(-1,1.5) as -pow(1,1.5), or -1. C allows
you to do so, but notice that you've now violated the usual
laws of exponents:
pow(x,a) * pow(x,b) == pow(x, a+b) /* mathematically */
so
pow(-1,1.5) * pow(-1,1.5)
== pow(-1,3.0)
== -1
but
xpow(-1,1.5) * xpow(-1,1.5)
== -pow(1,1.5) * -pow(1,1.5)
== -1 * -1
== 1
If you're happy with this state of affairs, go ahead and
be happy -- but don't ask the rest of the world to join in
your rejoicing.
--
Eric Sosman
lid