1 /* mpq_set_f -- set an mpq from an mpf.
3 Copyright 2000-2002 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
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
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/. */
37 mpq_set_f (mpq_ptr q
, mpf_srcptr f
)
39 mp_size_t fexp
= EXP(f
);
41 mp_size_t fsize
= SIZ(f
);
42 mp_size_t abs_fsize
= ABS(fsize
);
54 /* strip low zero limbs from f */
56 MPN_STRIP_LOW_ZEROS_NOT_ZERO (fptr
, abs_fsize
, flow
);
58 if (fexp
>= abs_fsize
)
60 /* radix point is to the right of the limbs, no denominator */
63 num_ptr
= MPZ_NEWALLOC (mpq_numref (q
), fexp
);
64 MPN_ZERO (num_ptr
, fexp
- abs_fsize
);
65 MPN_COPY (num_ptr
+ fexp
- abs_fsize
, fptr
, abs_fsize
);
67 SIZ(NUM(q
)) = fsize
>= 0 ? fexp
: -fexp
;
73 /* radix point is within or to the left of the limbs, use denominator */
74 mp_ptr num_ptr
, den_ptr
;
77 den_size
= abs_fsize
- fexp
;
78 num_ptr
= MPZ_NEWALLOC (mpq_numref (q
), abs_fsize
);
79 den_ptr
= MPZ_NEWALLOC (mpq_denref (q
), den_size
+1);
83 /* no powers of two to strip from numerator */
85 MPN_COPY (num_ptr
, fptr
, abs_fsize
);
86 MPN_ZERO (den_ptr
, den_size
);
87 den_ptr
[den_size
] = 1;
91 /* right shift numerator, adjust denominator accordingly */
95 count_trailing_zeros (shift
, flow
);
97 mpn_rshift (num_ptr
, fptr
, abs_fsize
, shift
);
98 abs_fsize
-= (num_ptr
[abs_fsize
-1] == 0);
100 MPN_ZERO (den_ptr
, den_size
);
101 den_ptr
[den_size
] = GMP_LIMB_HIGHBIT
>> (shift
-1);
104 SIZ(NUM(q
)) = fsize
>= 0 ? abs_fsize
: -abs_fsize
;
105 SIZ(DEN(q
)) = den_size
+ 1;