A couple of points about this program:

Karl F. Larsen wrote:

> double power(double a, int b)
> {
>       double pow = 1.0;
>       int i;
>       
>       if ( a == 0 )
>               return 0;

Performing `==' on a double is often something to be avoided. In this
case, it shouldn't matter; the program will deal with the case where a 
is zero. In general, it's often better to use

        if (fabs(a - b) < EPSILON)
than
        if (a == b)

where EPSILON is some small value.

>       if ( b == 0 )
>               return 1;

This shouldn't need to be a special case; `pow' is initialised to 1.0, 
so if b is zero, the for loops will never be executed, and 1.0 would
be returned.

>       if ( b < 0)
>       {
>               b = b * -1;     /* makes b a positive number */

Using `b = -b' may be more efficient than performing a multiply.

>               for( i=1; i <= b; i++)
>                       pow = pow * a;

This is a less than ideal way to compute powers. The time taken is
proportional to b, whereas you can easily do it in a time proportional 
to log[2](b).

The original algorithm is equivalent to computing a * b by adding a to
zero b times. In practice, multiplication is performed by breaking b
into powers of 2 (b0 + 2.b1 + 4.b2 + ..., where each bi is zero or
one), so

a*b     = a*(b0 + 2.b1 + 4.b2 + 8.b3 + ...)
        = b0.a + 2.b1.a + 4.b2.a + 8.b3.a + ...
        = b0.a + 2(b1.a + 2(b2.a + 2(b3.a + ...

Similarly, to compute an integral power, you break the exponent into
powers of two. Then:

a^b     = a^(b0 + 2.b1 + 4.b2 + 8.b3 + ...)
        = b0.a * b1.a^2 * b2.a^4 * b3.a^8 * ...
        = b0.a * a^2.(b1 * a^2.(b2 * a^2.(b3 * ...

Which can be computed using:

        double pow(double a, int b)
        {
                double pow = 1.0;
                int i;
        
                for (i = 0; i < 8*sizeof(int); i++)
                {
                        if (b & (1U << i))      /* if the ith bit of b is set */
                                pow *= a;
                        a *= a;                 /* a = a^2 */
                }
        
                return pow;
        }

However, all of this is general programming theory, rather than being
specific to C.

>       So this is where I am. And a question arises: Is this a Sig where
> my level of C programming development should be? Sure looks like You and
> others are way ahead of me. 

Well, there are the newsgroups comp.lang.c and comp.lang.c.moderated.
I don't know about mailing lists.

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to