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

cik at l.cc.purdue.edu.UUCP cik at l.cc.purdue.edu.UUCP
Fri Jul 1 12:51:44 AEST 1988


In article <3167 at ritcsh.UUCP>, gregory at ritcsh.UUCP (Gregory Conway) writes:
> In article <4778 at haddock.ISC.COM>, karl at haddock.ISC.COM (Karl Heuer) writes:
> ] 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),
> 
> I'm still a little wet behind the ears where C is concerned, so (politely)
> correct me if I'm wrong, but what's wrong with this:

 
> 		y = 3.0^2
> 		log (y) = log (3.0^2)
> 		log (y) = 2 * log(3.0)

> 		So......
> 
> 		y = exp ((double)2 * log(3.0));
> 
> Mathematically, it should work.  I'm just not so sure that it will compile.
> How about it??
> 
It will compile, and it will execute, and except for roundoff, it will give 
the right answer.  So why do I complain?

	y = 3.0^2

if properly compiled, takes 1 multiplication time.

 		y = exp ((double)2 * log(3.0));

takes 1 convert time, 2 function calls, two executions of transcendental
functions.  We are talking about 20-100 times as much execution time.
In addition, if instead we wanted

	n = 3^2

we would need two more convert times, and would the answer be 9 or 8?  I
do not know, and I cannot even guess.  If we want 3.0^2 to be an integer
in its floating point representation, we had better not use log and exp.
-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (ARPA or UUCP) or hrubin at purccvm.bitnet



More information about the Comp.lang.c mailing list