Path: utzoo!utgpu!water!watmath!clyde!rutgers!cmcl2!brl-adm!brl-smoke!gwyn From: gwyn@brl-smoke.ARPA (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: why just a power operator? Message-ID: <7024@brl-smoke.ARPA> Date: 11 Jan 88 07:43:48 GMT References: <3410@megaron.arizona.edu> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 72 In article <3410@megaron.arizona.edu> gmt@arizona.edu (Gregg Townsend) writes: >Why is everyone so interested in a power operator compared to, say, >square root or logarithm? Basically, it's because exponentiation involving one or two integers can usually be done much faster than through use of the floating-point pow() function, and in the common case **2 can be highly optimized. Also, as pointed out previously by someone else, pow() fails for converted integers for which the operation makes perfect sense. By the way, here is a generic integer-to-integer function written in "old C" that I sometimes find myself using (since the language doesn't take care of it for me); it uses the "binary exponent representation" trick mentioned in eralier messages: /* LPow -- long exponentiation (no overflow detection) last edit: 86/06/29 D A Gwyn SCCS ID: @(#)lpow.c 1.3 */ long LPow( base, exponent ) /* returns base^exponent */ register long base; register long exponent; { register long result; /* result accumulator */ /* handle simple special cases separately: */ if ( exponent == 0 ) return 1; /* includes 0^0 */ else if ( base == 0 ) return 0; /* exp. < 0 should be EDOM */ else if ( base == 1 ) return 1; else if ( base == -1 ) #if 0 /* intended code: */ return exponent % 2 == 0 ? 1 : -1; #else /* faster equivalent (suggested by Dan Levy of Teletype): */ return (exponent & 1) == 0 ? 1 : -1; #endif else if ( exponent < 0 ) return 0; /* general case with exponent > 0: */ result = 1; for ( ; ; ) /* LOOP INVARIANT: result*base^exponent */ { #if 0 /* intended code: */ if ( exponent % 2 != 0 ) #else /* faster equivalent (suggested by Dan Levy of Teletype): */ if ( (exponent & 1) != 0 ) #endif result *= base; #if 0 /* intended code: */ if ( (exponent /= 2) == 0 ) #else /* faster equivalent (suggested by Dan Levy of Teletype): */ if ( (exponent >>= 1) == 0 ) #endif break; /* result now stable */ base *= base; } return result; }