1 /* mpq_set_f -- set an mpq from an mpf.
3 Copyright 2000, 2001, 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 the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
26 mpq_set_f (mpq_ptr q, mpf_srcptr f)
28 mp_size_t fexp = EXP(f);
30 mp_size_t fsize = SIZ(f);
31 mp_size_t abs_fsize = ABS(fsize);
37 q->_mp_num._mp_size = 0;
38 q->_mp_den._mp_size = 1;
39 q->_mp_den._mp_d[0] = 1;
43 /* strip low zero limbs from f */
45 MPN_STRIP_LOW_ZEROS_NOT_ZERO (fptr, abs_fsize, flow);
47 if (fexp >= abs_fsize)
49 /* radix point is to the right of the limbs, no denominator */
52 MPZ_REALLOC (mpq_numref (q), fexp);
53 num_ptr = q->_mp_num._mp_d;
54 MPN_ZERO (num_ptr, fexp - abs_fsize);
55 MPN_COPY (num_ptr + fexp - abs_fsize, fptr, abs_fsize);
57 q->_mp_num._mp_size = fsize >= 0 ? fexp : -fexp;
58 q->_mp_den._mp_size = 1;
59 q->_mp_den._mp_d[0] = 1;
63 /* radix point is within or to the left of the limbs, use denominator */
64 mp_ptr num_ptr, den_ptr;
67 den_size = abs_fsize - fexp;
68 MPZ_REALLOC (mpq_numref (q), abs_fsize);
69 MPZ_REALLOC (mpq_denref (q), den_size+1);
70 num_ptr = q->_mp_num._mp_d;
71 den_ptr = q->_mp_den._mp_d;
75 /* no powers of two to strip from numerator */
77 MPN_COPY (num_ptr, fptr, abs_fsize);
78 MPN_ZERO (den_ptr, den_size);
79 den_ptr[den_size] = 1;
83 /* right shift numerator, adjust denominator accordingly */
87 count_trailing_zeros (shift, flow);
89 mpn_rshift (num_ptr, fptr, abs_fsize, shift);
90 abs_fsize -= (num_ptr[abs_fsize-1] == 0);
92 MPN_ZERO (den_ptr, den_size);
93 den_ptr[den_size] = GMP_LIMB_HIGHBIT >> (shift-1);
96 q->_mp_num._mp_size = fsize >= 0 ? abs_fsize : -abs_fsize;
97 q->_mp_den._mp_size = den_size + 1;