[comp.lang.c] Question regarding pow

tony@joshua.math.ucla.edu (02/01/89)

I am having a problem using the pow() function in Micrsoft C and
I was wondering if someone out there can point out what I am doing
wrong.

I'm trying to use the pow () function to raise negative one (-1)
to the power n, i.e. flip the sign back and forth.

What I'm doing is something like:

#include <math.h>
void foo () 
{
    int n ;

    for (n = 0 ; n < 10 ; n++)
        printf ("%lf",pow (-1,n)) ;

}

I am getting a "DOMAIN" error for each pow() call when I do this.  

According to my library guide, the pow function is defined as follows:

        double pow (x,y)
        double x ;
        double y ;

        ...If x is negative and y is not an integer, the function 
        prints a DOMAIN error message to stderr, sets errono to EDOM, 
        and returns 0...

My int n variable is being cast into a double, hence this error.
Can someone tell me how I can get around this?

(I know I can use if statements to see if the sign should be - or +
but I'd rather use the pow() function. Its more elegant...)

What is pow (0.,0.)?  I am getting a value 0 but shouldn't it be undefined?

gwyn@smoke.BRL.MIL (Doug Gwyn ) (02/02/89)

In article <400@sunset.MATH.UCLA.EDU> tony@MATH.UCLA.EDU () writes:
>I'm trying to use the pow () function to raise negative one (-1)
>to the power n, i.e. flip the sign back and forth.

That's an extremely expensive way to do it.
Try
	sign = n % 2 ? -1 : 1;
or, for a loop, initialize sign to 1 or -1 then just keep doing
	sign = -sign;

>        printf ("%lf",pow (-1,n)) ;

This is utterly dependent on the automatic coercion done under ANSI C
when a prototype is in scope.  If you were to port this to a pre-ANSI
C environment, the arguments to pow() would not be coerced to doubles
and therefore would be imported by pow() as garbage values.  In fact
maybe your current compiler (with which I'm not familiar) doesn't
coerce the argument types, in which case it could explain your problem.

>(I know I can use if statements to see if the sign should be - or +
>but I'd rather use the pow() function. Its more elegant...)

Like hell it is.

>What is pow (0.,0.)?  I am getting a value 0 but shouldn't it be undefined?

Really 0^0 should be treated as 1 for most applications.