home *** CD-ROM | disk | FTP | other *** search
- /* powi.c
- *
- * Real raised to integer power
- *
- *
- *
- * SYNOPSIS:
- *
- * double x, y, powi();
- * int n;
- *
- * y = powi( x, n );
- *
- *
- *
- * DESCRIPTION:
- *
- * Returns argument x raised to the nth power.
- * The routine efficiently decomposes n as a sum of powers of
- * two. The desired power is a product of two-to-the-kth
- * powers of x. Thus to compute the 32767 power of x requires
- * 28 multiplications instead of 32767 multiplications.
- *
- *
- *
- * ACCURACY:
- *
- * Approximately 1e-16 relative.
- *
- * Returns MAXNUM or zero on overflow, which is detected
- * by integer estimation of the exponent of the result.
- *
- */
-
- /* powi.c */
-
- /* Cephes Math Library Release 1.1: March, 1985
- * Copyright 1985 by Stephen L. Moshier
- * Contributed to BIX for personal, noncommercial use only.
- * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
-
- extern double MAXNUM, MAXLOG;
-
- double powi( x, n )
- double x;
- int n;
- {
- int e, sign, asign;
- short *p;
- double w, y;
- double log();
-
- if( x == 0.0 )
- {
- if( n == 0 )
- return( 1.0 );
- else if( n < 0 )
- return( MAXNUM );
- else
- return( 0.0 );
- }
-
- if( n == 0 )
- return( 1.0 );
-
-
- if( x < 0.0 )
- {
- asign = -1;
- x = -x;
- }
- else
- asign = 0;
-
-
- if( n < 0 )
- {
- sign = -1;
- n = -n;
- x = 1.0/x;
- }
- else
- sign = 0;
-
- /* powi.c */
-
- /* First bit of the power */
- if( n & 1 )
- y = x;
-
- else
- {
- y = 1.0;
- asign = 0;
- }
-
- w = n * log( x ); /* Overflow detection */
- if( w >= MAXLOG )
- {
- y = MAXNUM;
- goto done;
- }
- if( w < -MAXLOG )
- return(0.0);
-
- w = x;
- n >>= 1;
- while( n )
- {
- w = w * w; /* arg to the 2-to-the-kth power */
- if( n & 1 ) /* if that bit is set, then include in product */
- y *= w;
- n >>= 1;
- }
-
-
- done:
-
- if( asign )
- return( -y ); /* odd power of negative number */
-
- return(y);
- }
-