New module 'ceilf'.
[gnulib.git] / lib / ceil.c
1 /* Round towards positive infinity.
2    Copyright (C) 2007 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Bruno Haible <bruno@clisp.org>, 2007.  */
19
20 #include <config.h>
21
22 /* Specification.  */
23 #include <math.h>
24
25 #include <float.h>
26
27 #ifdef USE_LONG_DOUBLE
28 # define FUNC ceill
29 # define DOUBLE long double
30 # define MANT_DIG LDBL_MANT_DIG
31 # define L_(literal) literal##L
32 #elif ! defined USE_FLOAT
33 # define FUNC ceil
34 # define DOUBLE double
35 # define MANT_DIG DBL_MANT_DIG
36 # define L_(literal) literal
37 #else /* defined USE_FLOAT */
38 # define FUNC ceilf
39 # define DOUBLE float
40 # define MANT_DIG FLT_MANT_DIG
41 # define L_(literal) literal##f
42 #endif
43
44 /* 2^(MANT_DIG-1).  */
45 static const double TWO_MANT_DIG =
46   /* Assume MANT_DIG <= 5 * 31.
47      Use the identity
48        n = floor(n/5) + floor((n+1)/5) + ... + floor((n+4)/5).  */
49   (DOUBLE) (1U << ((MANT_DIG - 1) / 5))
50   * (DOUBLE) (1U << ((MANT_DIG - 1 + 1) / 5))
51   * (DOUBLE) (1U << ((MANT_DIG - 1 + 2) / 5))
52   * (DOUBLE) (1U << ((MANT_DIG - 1 + 3) / 5))
53   * (DOUBLE) (1U << ((MANT_DIG - 1 + 4) / 5));
54
55 DOUBLE
56 FUNC (DOUBLE x)
57 {
58   /* The use of 'volatile' guarantees that excess precision bits are dropped
59      at each addition step and before the following comparison at the caller's
60      site.  It is necessary on x86 systems where double-floats are not IEEE
61      compliant by default, to avoid that the results become platform and compiler
62      option dependent.  'volatile' is a portable alternative to gcc's
63      -ffloat-store option.  */
64   volatile DOUBLE y = x;
65   volatile DOUBLE z = y;
66
67   /* Round to the next integer (nearest or up or down, doesn't matter).  */
68   if (z > L_(0.0))
69     {
70       z += TWO_MANT_DIG;
71       z -= TWO_MANT_DIG;
72     }
73   else if (z < L_(0.0))
74     {
75       z -= TWO_MANT_DIG;
76       z += TWO_MANT_DIG;
77     }
78   /* Enforce rounding up.  */
79   if (z < y)
80     z += L_(1.0);
81
82   return z;
83 }