| 1 | /* Round to nearest integer value, rounding halfway cases to even. |
| 2 | dbl-64/wordsize-64 version. |
| 3 | Copyright (C) 2016-2019 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 <libm-alias-double.h> |
| 23 | #include <stdint.h> |
| 24 | |
| 25 | #define BIAS 0x3ff |
| 26 | #define MANT_DIG 53 |
| 27 | #define MAX_EXP (2 * BIAS + 1) |
| 28 | |
| 29 | double |
| 30 | __roundeven (double x) |
| 31 | { |
| 32 | uint64_t ix, ux; |
| 33 | EXTRACT_WORDS64 (ix, x); |
| 34 | ux = ix & 0x7fffffffffffffffULL; |
| 35 | int exponent = ux >> (MANT_DIG - 1); |
| 36 | if (exponent >= BIAS + MANT_DIG - 1) |
| 37 | { |
| 38 | /* Integer, infinity or NaN. */ |
| 39 | if (exponent == MAX_EXP) |
| 40 | /* Infinity or NaN; quiet signaling NaNs. */ |
| 41 | return x + x; |
| 42 | else |
| 43 | return x; |
| 44 | } |
| 45 | else if (exponent >= BIAS) |
| 46 | { |
| 47 | /* At least 1; not necessarily an integer. Locate the bits with |
| 48 | exponents 0 and -1 (when the unbiased exponent is 0, the bit |
| 49 | with exponent 0 is implicit, but as the bias is odd it is OK |
| 50 | to take it from the low bit of the exponent). */ |
| 51 | int int_pos = (BIAS + MANT_DIG - 1) - exponent; |
| 52 | int half_pos = int_pos - 1; |
| 53 | uint64_t half_bit = 1ULL << half_pos; |
| 54 | uint64_t int_bit = 1ULL << int_pos; |
| 55 | if ((ix & (int_bit | (half_bit - 1))) != 0) |
| 56 | /* Carry into the exponent works correctly. No need to test |
| 57 | whether HALF_BIT is set. */ |
| 58 | ix += half_bit; |
| 59 | ix &= ~(int_bit - 1); |
| 60 | } |
| 61 | else if (exponent == BIAS - 1 && ux > 0x3fe0000000000000ULL) |
| 62 | /* Interval (0.5, 1). */ |
| 63 | ix = (ix & 0x8000000000000000ULL) | 0x3ff0000000000000ULL; |
| 64 | else |
| 65 | /* Rounds to 0. */ |
| 66 | ix &= 0x8000000000000000ULL; |
| 67 | INSERT_WORDS64 (x, ix); |
| 68 | return x; |
| 69 | } |
| 70 | hidden_def (__roundeven) |
| 71 | libm_alias_double (__roundeven, roundeven) |
| 72 | |