beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpq / set_f.c
blob7764a17f05e1cc4218732fc558dfd80e26d371cd
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
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"
33 #include "longlong.h"
36 void
37 mpq_set_f (mpq_ptr q, mpf_srcptr f)
39 mp_size_t fexp = EXP(f);
40 mp_ptr fptr = PTR(f);
41 mp_size_t fsize = SIZ(f);
42 mp_size_t abs_fsize = ABS(fsize);
43 mp_limb_t flow;
45 if (fsize == 0)
47 /* set q=0 */
48 SIZ(NUM(q)) = 0;
49 SIZ(DEN(q)) = 1;
50 PTR(DEN(q))[0] = 1;
51 return;
54 /* strip low zero limbs from f */
55 flow = *fptr;
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 */
61 mp_ptr num_ptr;
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;
68 SIZ(DEN(q)) = 1;
69 PTR(DEN(q))[0] = 1;
71 else
73 /* radix point is within or to the left of the limbs, use denominator */
74 mp_ptr num_ptr, den_ptr;
75 mp_size_t den_size;
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);
81 if (flow & 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;
89 else
91 /* right shift numerator, adjust denominator accordingly */
92 int shift;
94 den_size--;
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;