NEWS.stable: log cherry-pick [ae006b4]->[4a9738e] strtoimax: Avoid link error on...
[gnulib.git] / lib / ldexpl.c
1 /* Emulation for ldexpl.
2    Contributed by Paolo Bonzini
3
4    Copyright 2002-2003, 2007-2011 Free Software Foundation, Inc.
5
6    This file is part of gnulib.
7
8    This program is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include <math.h>
25
26 #include <float.h>
27 #include "fpucw.h"
28
29 long double
30 ldexpl (long double x, int exp)
31 {
32   long double factor;
33   int bit;
34   DECL_LONG_DOUBLE_ROUNDING
35
36   BEGIN_LONG_DOUBLE_ROUNDING ();
37
38   /* Check for zero, nan and infinity. */
39   if (!(isnanl (x) || x + x == x))
40     {
41       if (exp < 0)
42         {
43           exp = -exp;
44           factor = 0.5L;
45         }
46       else
47         factor = 2.0L;
48
49       if (exp > 0)
50         for (bit = 1;;)
51           {
52             /* Invariant: Here bit = 2^i, factor = 2^-2^i or = 2^2^i,
53                and bit <= exp.  */
54             if (exp & bit)
55               x *= factor;
56             bit <<= 1;
57             if (bit > exp)
58               break;
59             factor = factor * factor;
60           }
61     }
62
63   END_LONG_DOUBLE_ROUNDING ();
64
65   return x;
66 }
67
68 #if 0
69 int
70 main (void)
71 {
72   long double x;
73   int y;
74   for (y = 0; y < 29; y++)
75     printf ("%5d %.16Lg %.16Lg\n", y, ldexpl (0.8L, y), ldexpl (0.8L, -y) * ldexpl (0.8L, y));
76 }
77 #endif