1 | /* Round to nearest integer value, rounding halfway cases to even. |
2 | ldbl-128ibm version. |
3 | Copyright (C) 2016-2024 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 | <https://www.gnu.org/licenses/>. */ |
19 | |
20 | #define NO_MATH_REDIRECT |
21 | #include <math.h> |
22 | #include <math_private.h> |
23 | |
24 | long double |
25 | __roundevenl (long double x) |
26 | { |
27 | double xh, xl, hi; |
28 | |
29 | ldbl_unpack (x, &xh, &xl); |
30 | |
31 | if (xh != 0 && isfinite (xh)) |
32 | { |
33 | hi = __roundeven (x: xh); |
34 | if (hi != xh) |
35 | { |
36 | /* The high part is not an integer; the low part only |
37 | affects the result if the high part is exactly half way |
38 | between two integers and the low part is nonzero in the |
39 | opposite direction to the rounding of the high part. */ |
40 | double diff = hi - xh; |
41 | if (fabs (x: diff) == 0.5) |
42 | { |
43 | if (xl < 0 && diff > 0) |
44 | xh = hi - 1; |
45 | else if (xl > 0 && diff < 0) |
46 | xh = hi + 1; |
47 | else |
48 | xh = hi; |
49 | } |
50 | else |
51 | xh = hi; |
52 | xl = 0; |
53 | } |
54 | else |
55 | { |
56 | /* The high part is a nonzero integer. Rounding the low |
57 | part to nearest, ties round to even, is always correct, |
58 | as a high part that is an odd integer together with a low |
59 | part with magnitude 0.5 is not a valid long double. */ |
60 | xl = __roundeven (x: xl); |
61 | xh = hi; |
62 | ldbl_canonicalize_int (&xh, &xl); |
63 | } |
64 | } |
65 | else |
66 | /* Quiet signaling NaN arguments. */ |
67 | xh += xh; |
68 | |
69 | return ldbl_pack (xh, xl); |
70 | } |
71 | weak_alias (__roundevenl, roundevenl) |
72 | |