github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/mpq/set_f.c (about) 1 /* mpq_set_f -- set an mpq from an mpf. 2 3 Copyright 2000-2002 Free Software Foundation, Inc. 4 5 This file is part of the GNU MP Library. 6 7 The GNU MP Library is free software; you can redistribute it and/or modify 8 it under the terms of either: 9 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. 13 14 or 15 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. 19 20 or both in parallel, as here. 21 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. 26 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/. */ 30 31 #include "gmp.h" 32 #include "gmp-impl.h" 33 #include "longlong.h" 34 35 36 void 37 mpq_set_f (mpq_ptr q, mpf_srcptr f) 38 { 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; 44 45 if (fsize == 0) 46 { 47 /* set q=0 */ 48 SIZ(NUM(q)) = 0; 49 SIZ(DEN(q)) = 1; 50 PTR(DEN(q))[0] = 1; 51 return; 52 } 53 54 /* strip low zero limbs from f */ 55 flow = *fptr; 56 MPN_STRIP_LOW_ZEROS_NOT_ZERO (fptr, abs_fsize, flow); 57 58 if (fexp >= abs_fsize) 59 { 60 /* radix point is to the right of the limbs, no denominator */ 61 mp_ptr num_ptr; 62 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); 66 67 SIZ(NUM(q)) = fsize >= 0 ? fexp : -fexp; 68 SIZ(DEN(q)) = 1; 69 PTR(DEN(q))[0] = 1; 70 } 71 else 72 { 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; 76 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); 80 81 if (flow & 1) 82 { 83 /* no powers of two to strip from numerator */ 84 85 MPN_COPY (num_ptr, fptr, abs_fsize); 86 MPN_ZERO (den_ptr, den_size); 87 den_ptr[den_size] = 1; 88 } 89 else 90 { 91 /* right shift numerator, adjust denominator accordingly */ 92 int shift; 93 94 den_size--; 95 count_trailing_zeros (shift, flow); 96 97 mpn_rshift (num_ptr, fptr, abs_fsize, shift); 98 abs_fsize -= (num_ptr[abs_fsize-1] == 0); 99 100 MPN_ZERO (den_ptr, den_size); 101 den_ptr[den_size] = GMP_LIMB_HIGHBIT >> (shift-1); 102 } 103 104 SIZ(NUM(q)) = fsize >= 0 ? abs_fsize : -abs_fsize; 105 SIZ(DEN(q)) = den_size + 1; 106 } 107 }