xref: /openbsd-src/lib/libm/src/s_scalbn.c (revision 043fbe51c197dbbcd422e917b65f765d8b5f8874)
1 /* @(#)s_scalbn.c 5.1 93/09/24 */
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunPro, a Sun Microsystems, Inc. business.
7  * Permission to use, copy, modify, and distribute this
8  * software is freely granted, provided that this notice
9  * is preserved.
10  * ====================================================
11  */
12 
13 /*
14  * scalbn (double x, int n)
15  * scalbn(x,n) returns x* 2**n  computed by  exponent
16  * manipulation rather than by actually performing an
17  * exponentiation or a multiplication.
18  */
19 
20 #include <sys/cdefs.h>
21 #include <float.h>
22 #include <math.h>
23 
24 #include "math_private.h"
25 
26 static const double
27 two54   =  1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */
28 twom54  =  5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */
29 huge   = 1.0e+300,
30 tiny   = 1.0e-300;
31 
32 double
33 scalbn (double x, int n)
34 {
35 	int32_t k,hx,lx;
36 	EXTRACT_WORDS(hx,lx,x);
37         k = (hx&0x7ff00000)>>20;		/* extract exponent */
38         if (k==0) {				/* 0 or subnormal x */
39             if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */
40 	    x *= two54;
41 	    GET_HIGH_WORD(hx,x);
42 	    k = ((hx&0x7ff00000)>>20) - 54;
43             if (n< -50000) return tiny*x; 	/*underflow*/
44 	    }
45         if (k==0x7ff) return x+x;		/* NaN or Inf */
46         k = k+n;
47         if (k >  0x7fe) return huge*copysign(huge,x); /* overflow  */
48         if (k > 0) 				/* normal result */
49 	    {SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;}
50         if (k <= -54)
51             if (n > 50000) 	/* in case integer overflow in n+k */
52 		return huge*copysign(huge,x);	/*overflow*/
53 	    else return tiny*copysign(tiny,x); 	/*underflow*/
54         k += 54;				/* subnormal result */
55 	SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20));
56         return x*twom54;
57 }
58 
59 #if LDBL_MANT_DIG == 53
60 #ifdef __weak_alias
61 __weak_alias(scalbnl, scalbn);
62 #endif /* __weak_alias */
63 #endif /* LDBL_MANT_DIG == 53 */
64