Path: utzoo!utgpu!water!watmath!clyde!bellcore!faline!thumper!ulysses!andante!mit-eddie!bu-cs!purdue!i.cc.purdue.edu!k.cc.purdue.edu!l.cc.purdue.edu!cik From: cik@l.cc.purdue.edu.UUCP Newsgroups: comp.lang.c Subject: Re: Exponentiation in C (was: How not to write a loop) Summary: It is so slow, and might not give an integer because of roundoff Message-ID: <820@l.cc.purdue.edu> Date: 1 Jul 88 02:51:44 GMT References: <16276@brl-adm.ARPA> <329@accelerator.eng.ohio-state.edu> <3167@ritcsh.UUCP> Organization: Purdue University Statistics Department Lines: 44 In article <3167@ritcsh.UUCP>, gregory@ritcsh.UUCP (Gregory Conway) writes: > In article <4778@haddock.ISC.COM>, karl@haddock.ISC.COM (Karl Heuer) writes: > ] In article <808@l.cc.purdue.edu> cik@l.cc.purdue.edu (Herman Rubin) writes: > ] >In article <12784@apple.Apple.COM>, bgibbons@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@l.cc.purdue.edu (ARPA or UUCP) or hrubin@purccvm.bitnet