1/* Round to nearest integer value, rounding halfway cases to even.
2 flt-32 version.
3 Copyright (C) 2016-2017 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <http://www.gnu.org/licenses/>. */
19
20#include <math.h>
21#include <math_private.h>
22#include <stdint.h>
23
24#define BIAS 0x7f
25#define MANT_DIG 24
26#define MAX_EXP (2 * BIAS + 1)
27
28float
29roundevenf (float x)
30{
31 uint32_t ix, ux;
32 GET_FLOAT_WORD (ix, x);
33 ux = ix & 0x7fffffff;
34 int exponent = ux >> (MANT_DIG - 1);
35 if (exponent >= BIAS + MANT_DIG - 1)
36 {
37 /* Integer, infinity or NaN. */
38 if (exponent == MAX_EXP)
39 /* Infinity or NaN; quiet signaling NaNs. */
40 return x + x;
41 else
42 return x;
43 }
44 else if (exponent >= BIAS)
45 {
46 /* At least 1; not necessarily an integer. Locate the bits with
47 exponents 0 and -1 (when the unbiased exponent is 0, the bit
48 with exponent 0 is implicit, but as the bias is odd it is OK
49 to take it from the low bit of the exponent). */
50 int int_pos = (BIAS + MANT_DIG - 1) - exponent;
51 int half_pos = int_pos - 1;
52 uint32_t half_bit = 1U << half_pos;
53 uint32_t int_bit = 1U << int_pos;
54 if ((ix & (int_bit | (half_bit - 1))) != 0)
55 /* Carry into the exponent works correctly. No need to test
56 whether HALF_BIT is set. */
57 ix += half_bit;
58 ix &= ~(int_bit - 1);
59 }
60 else if (exponent == BIAS - 1 && ux > 0x3f000000)
61 /* Interval (0.5, 1). */
62 ix = (ix & 0x80000000) | 0x3f800000;
63 else
64 /* Rounds to 0. */
65 ix &= 0x80000000;
66 SET_FLOAT_WORD (x, ix);
67 return x;
68}
69