beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpf / ceilfloor.c
blob302e2b8ae5a845ab298ceed94661c48b3fe7f6e9
1 /* mpf_ceil, mpf_floor -- round an mpf to an integer.
3 Copyright 2001, 2004, 2012 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
35 /* dir==1 for ceil, dir==-1 for floor
37 Notice the use of prec+1 ensures mpf_ceil and mpf_floor are equivalent to
38 mpf_set if u is already an integer. */
40 static void __gmpf_ceil_or_floor (REGPARM_2_1 (mpf_ptr, mpf_srcptr, int)) REGPARM_ATTR (1);
41 #define mpf_ceil_or_floor(r,u,dir) __gmpf_ceil_or_floor (REGPARM_2_1 (r, u, dir))
43 REGPARM_ATTR (1) static void
44 mpf_ceil_or_floor (mpf_ptr r, mpf_srcptr u, int dir)
46 mp_ptr rp, up, p;
47 mp_size_t size, asize, prec;
48 mp_exp_t exp;
50 size = SIZ(u);
51 if (size == 0)
53 zero:
54 SIZ(r) = 0;
55 EXP(r) = 0;
56 return;
59 rp = PTR(r);
60 exp = EXP(u);
61 if (exp <= 0)
63 /* u is only a fraction */
64 if ((size ^ dir) < 0)
65 goto zero;
66 rp[0] = 1;
67 EXP(r) = 1;
68 SIZ(r) = dir;
69 return;
71 EXP(r) = exp;
73 up = PTR(u);
74 asize = ABS (size);
75 up += asize;
77 /* skip fraction part of u */
78 asize = MIN (asize, exp);
80 /* don't lose precision in the copy */
81 prec = PREC (r) + 1;
83 /* skip excess over target precision */
84 asize = MIN (asize, prec);
86 up -= asize;
88 if ((size ^ dir) >= 0)
90 /* rounding direction matches sign, must increment if ignored part is
91 non-zero */
92 for (p = PTR(u); p != up; p++)
94 if (*p != 0)
96 if (mpn_add_1 (rp, up, asize, CNST_LIMB(1)))
98 /* was all 0xFF..FFs, which have become zeros, giving just
99 a carry */
100 rp[0] = 1;
101 asize = 1;
102 EXP(r)++;
104 SIZ(r) = (size >= 0 ? asize : -asize);
105 return;
110 SIZ(r) = (size >= 0 ? asize : -asize);
111 if (rp != up)
112 MPN_COPY_INCR (rp, up, asize);
116 void
117 mpf_ceil (mpf_ptr r, mpf_srcptr u)
119 mpf_ceil_or_floor (r, u, 1);
122 void
123 mpf_floor (mpf_ptr r, mpf_srcptr u)
125 mpf_ceil_or_floor (r, u, -1);