Home | History | Annotate | Line # | Download | only in src
      1 /* mpfr_get_q -- get a multiple-precision rational from
      2                  a floating-point number
      3 
      4 Copyright 2004, 2006-2023 Free Software Foundation, Inc.
      5 Contributed by the AriC and Caramba projects, INRIA.
      6 
      7 This file is part of the GNU MPFR Library.
      8 
      9 The GNU MPFR Library is free software; you can redistribute it and/or modify
     10 it under the terms of the GNU Lesser General Public License as published by
     11 the Free Software Foundation; either version 3 of the License, or (at your
     12 option) any later version.
     13 
     14 The GNU MPFR Library is distributed in the hope that it will be useful, but
     15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
     17 License for more details.
     18 
     19 You should have received a copy of the GNU Lesser General Public License
     20 along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
     21 https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
     22 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
     23 
     24 #include "mpfr-impl.h"
     25 
     26 #ifndef MPFR_USE_MINI_GMP
     27 /* part of the code was copied from get_z.c */
     28 void
     29 mpfr_get_q (mpq_ptr q, mpfr_srcptr f)
     30 {
     31   mpfr_exp_t exp;
     32   mpz_ptr u = mpq_numref (q);
     33   mpz_ptr v = mpq_denref (q);
     34 
     35   /* v is set to 1 and will not be changed directly.
     36      This ensures that q will be canonical. */
     37   mpz_set_ui (v, 1);
     38 
     39   if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (f)))
     40     {
     41       if (MPFR_UNLIKELY (MPFR_NOTZERO (f)))
     42         MPFR_SET_ERANGEFLAG ();
     43       mpz_set_ui (u, 0);
     44       /* The ternary value is 0 even for infinity. Giving the rounding
     45          direction in this case would not make much sense anyway, and
     46          the direction would not necessarily match rnd. */
     47     }
     48   else
     49     {
     50       exp = mpfr_get_z_2exp (u, f);
     51       if (exp >= 0)
     52         {
     53           MPFR_ASSERTN (exp <= (mp_bitcnt_t) -1);
     54           mpz_mul_2exp (u, u, exp);
     55         }
     56       else  /* exp < 0 */
     57         {
     58           MPFR_ASSERTN (-exp <= (mp_bitcnt_t) -1);
     59           mpq_div_2exp (q, q, -exp);
     60         }
     61     }
     62 }
     63 #endif
     64