Import mpfr-2.4.1
[dragonfly.git] / contrib / mpfr / get_z_exp.c
1 /* mpfr_get_z_exp -- get a multiple-precision integer and an exponent
2                      from a floating-point number
3
4 Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5 Contributed by the Arenaire and Cacao 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 2.1 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.LIB.  If not, write to
21 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
22 MA 02110-1301, USA. */
23
24 #include "mpfr-impl.h"
25
26 /* puts the mantissa of f into z, and returns 'exp' such that f = z * 2^exp
27  *
28  * 0 doesn't have an exponent, therefore the returned exponent in this case
29  * isn't really important. We choose to return __gmpfr_emin because
30  *   1) it is in the exponent range [__gmpfr_emin,__gmpfr_emax],
31  *   2) the smaller a number is (in absolute value), the smaller its
32  *      exponent is. In other words, the f -> exp function is monotonous
33  *      on nonnegative numbers.
34  * Note that this is different from the C function frexp().
35  */
36
37 mp_exp_t
38 mpfr_get_z_exp (mpz_ptr z, mpfr_srcptr f)
39 {
40   mp_size_t fn;
41   int sh;
42
43   MPFR_ASSERTD (MPFR_IS_FP (f));
44
45   if (MPFR_UNLIKELY (MPFR_IS_ZERO (f)))
46     {
47       mpz_set_ui (z, 0);
48       return __gmpfr_emin;
49     }
50
51   fn = MPFR_LIMB_SIZE(f);
52
53   /* check whether allocated space for z is enough */
54   if (MPFR_UNLIKELY (ALLOC (z) < fn))
55     MPZ_REALLOC (z, fn);
56
57   MPFR_UNSIGNED_MINUS_MODULO (sh, MPFR_PREC (f));
58   if (MPFR_LIKELY (sh))
59     mpn_rshift (PTR (z), MPFR_MANT (f), fn, sh);
60   else
61     MPN_COPY (PTR (z), MPFR_MANT (f), fn);
62
63   SIZ(z) = MPFR_IS_NEG (f) ? -fn : fn;
64
65   /* Test if the result is representable. Later, we could choose
66      to return MPFR_EXP_MIN if it isn't, or perhaps MPFR_EXP_MAX
67      to signal an error. The mantissa would still be meaningful. */
68   MPFR_ASSERTD ((mp_exp_unsigned_t) MPFR_GET_EXP (f) - MPFR_EXP_MIN
69                 >= (mp_exp_unsigned_t) MPFR_PREC(f));
70
71   return MPFR_GET_EXP (f) - MPFR_PREC (f);
72 }