1/* mpfr_get_z -- get a multiple-precision integer from
2                 a floating-point number
3
4Copyright 2004, 2006-2023 Free Software Foundation, Inc.
5Contributed by the AriC and Caramba projects, INRIA.
6
7This file is part of the GNU MPFR Library.
8
9The GNU MPFR Library is free software; you can redistribute it and/or modify
10it under the terms of the GNU Lesser General Public License as published by
11the Free Software Foundation; either version 3 of the License, or (at your
12option) any later version.
13
14The GNU MPFR Library is distributed in the hope that it will be useful, but
15WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17License for more details.
18
19You should have received a copy of the GNU Lesser General Public License
20along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
21https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
2251 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
23
24#include "mpfr-impl.h"
25
26int
27mpfr_get_z (mpz_ptr z, mpfr_srcptr f, mpfr_rnd_t rnd)
28{
29  int inex;
30  mpfr_t r;
31  mpfr_exp_t exp;
32  MPFR_SAVE_EXPO_DECL (expo);
33
34  if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (f)))
35    {
36      if (MPFR_UNLIKELY (MPFR_NOTZERO (f)))
37        MPFR_SET_ERANGEFLAG ();
38      mpz_set_ui (z, 0);
39      /* The ternary value is 0 even for infinity. Giving the rounding
40         direction in this case would not make much sense anyway, and
41         the direction would not necessarily match rnd. */
42      return 0;
43    }
44
45  MPFR_SAVE_EXPO_MARK (expo);
46
47  exp = MPFR_GET_EXP (f);
48  /* if exp <= 0, then |f|<1, thus |o(f)|<=1 */
49  MPFR_ASSERTN (exp < 0 || exp <= MPFR_PREC_MAX);
50  mpfr_init2 (r, (exp < (mpfr_exp_t) MPFR_PREC_MIN ?
51                  MPFR_PREC_MIN : (mpfr_prec_t) exp));
52  inex = mpfr_rint (r, f, rnd);
53  MPFR_ASSERTN (inex != 1 && inex != -1); /* integral part of f is
54                                             representable in r */
55  MPFR_ASSERTN (MPFR_IS_FP (r));
56
57  /* The flags from mpfr_rint are the wanted ones. In particular,
58     it sets the inexact flag when necessary. */
59  MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, __gmpfr_flags);
60
61  exp = mpfr_get_z_2exp (z, r);
62  if (exp >= 0)
63    mpz_mul_2exp (z, z, exp);
64  else
65    mpz_fdiv_q_2exp (z, z, -exp);
66  mpfr_clear (r);
67
68  MPFR_SAVE_EXPO_FREE (expo);
69
70  return inex;
71}
72