New module 'trunc'.
[pspp] / lib / trunc.c
1 /* Round towards zero.
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 /* 2^(DBL_MANT_DIG-1).  */
28 static const double TWO_MANT_DIG =
29   /* Assume DBL_MANT_DIG <= 4 * 31.
30      Use the identity
31        n = floor(n/4) + floor((n+1)/4) + floor((n+2)/4) + floor((n+3)/4).  */
32   (double) (1U << ((DBL_MANT_DIG - 1) / 4))
33   * (double) (1U << ((DBL_MANT_DIG - 1 + 1) / 4))
34   * (double) (1U << ((DBL_MANT_DIG - 1 + 2) / 4))
35   * (double) (1U << ((DBL_MANT_DIG - 1 + 3) / 4));
36
37 double
38 trunc (double x)
39 {
40   /* The use of 'volatile' guarantees that excess precision bits are dropped
41      at each addition step and before the following comparison at the caller's
42      site.  It is necessary on x86 systems where double-floats are not IEEE
43      compliant by default, to avoid that the results become platform and compiler
44      option dependent.  'volatile' is a portable alternative to gcc's
45      -ffloat-store option.  */
46   volatile double y = x;
47   volatile double z = y;
48
49   if (z > 0)
50     {
51       /* Round to the next integer (nearest or up or down, doesn't matter).  */
52       z += TWO_MANT_DIG;
53       z -= TWO_MANT_DIG;
54       /* Enforce rounding down.  */
55       if (z > y)
56         z -= 1.0;
57     }
58   else if (z < 0)
59     {
60       /* Round to the next integer (nearest or up or down, doesn't matter).  */
61       z -= TWO_MANT_DIG;
62       z += TWO_MANT_DIG;
63       /* Enforce rounding up.  */
64       if (z < y)
65         z += 1.0;
66     }
67   return z;
68 }