Xref: utzoo comp.lang.c:6372 junk:895 Path: utzoo!utgpu!water!watmath!clyde!rutgers!mcnc!decvax!decwrl!granite!jmd From: jmd@granite.dec.com (John Danskin) Newsgroups: comp.lang.c,sci.math.num-analysis Subject: Re: Power (Re: all those :-) Keywords: No need, No good, NO! (This is new; read it!) Message-ID: <175@granite.dec.com> Date: 19 Jan 88 19:00:33 GMT References: <302@Aragorn.dde.uucp> Reply-To: jmd@granite.UUCP (John Danskin) Organization: DEC Workstation Systems Engineering Lines: 52 In article <302@Aragorn.dde.uucp> be@dde.uucp (Bjorn Engsig) writes: >Let me start to comment on power with integer exponents. > >Pick up any first grade textbook on numerical analysis, and you will >be told NEVER to use a power function like that. First, if you need to >calculate x ** n (fortran notation), you will most often need >x ** (n-1) etc. as well, and it should be calculated using recursion, .... Why do you think the compiler would generate n * log(x) for x^n where n is an integer? The compiler knows that 'n' is an integer, and is free to generate the most efficient code that it can -> including iterative loops. x^n ==> { tmp = x; odd = 1; if (n > 0) { if (n & 1) { odd = x; } while (n) { tmp = tmp * tmp; n = n >> 1; } return tmp * odd; } else if (n < 0) { return (1/(x^-n)); } else { /* n == 0 */ return 1.; } } this generates perfectly reasonable code (yes, it can be improved 8-))) for x^n where n is an integer. If n is known to be a constant, then the compiler can generate optimal code for the integer power computation. If you want x^r where r is a double or float, the compiler can generate the appropriate log and exp calls.... So maybe you can elaborate on your difficulty with an exponentiation operator in light of the surprising ability of compilers to generate reasonable code. John Danskin decwrl!jmd