Exponentiation in C (was: How not to write a loop)

Karl Heuer karl at haddock.ISC.COM
Tue Jun 28 08:40:55 AEST 1988


In article <808 at l.cc.purdue.edu> cik at l.cc.purdue.edu (Herman Rubin) writes:
>In article <12784 at apple.Apple.COM>, bgibbons at Apple.COM (Bill Gibbons) writes:
>>... raising a floating-point value to an integer (typed as integer) power is
>>always done with repeated multiplies (in about log2(exponent) time),

That's a strange comment to be posting to a C newsgroup.

>Apparently Bill missed the discussion a few months ago about exponentiation
>in C.  There was considerable disagreement about what should be done about
>the problem, and a rather large number of correspondents seemed unable to
>consider computing powers except by the pow(x,y) function, which does not
>use the reasonably quick and exact method.

Actually that's an implementation issue; as has been noted, a smart compiler
could generate a single integer multiply instruction for an expression like
"(int)pow((double)n, 2.0)".

However, until a substantial fraction of available compilers actually do such
an optimization, I'd rather write "n*n" (or, if the expression n is complex
enough, "temp=n" and "temp*temp").  Using pow() is a small win if the compiler
is smart, but a big lose if it isn't.

I've managed to convince myself that C should have a real power operator.  It
won't get into ANSI C-88.  (Unless it was added in the second public review,
which I doubt.  Was it even formally proposed?  I didn't have time to write a
formal comment on this issue.)  The next best thing is to try it out as a
non-standard extension.

Perhaps the FSF would be interested in adding this to gcc.  If someone mails
me the appropriate address, I'll send them my analysis and suggestions.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list