beta-0.89.2
[luatex.git] / source / libs / mpfr / mpfr-3.1.3 / src / ui_pow_ui.c
blobeabb1fba8b88e34c2fed19b239c4666534528c6e
1 /* mpfr_ui_pow_ui -- compute the power beetween two machine integer
3 Copyright 1999-2015 Free Software Foundation, Inc.
4 Contributed by the AriC and Caramel projects, INRIA.
6 This file is part of the GNU MPFR Library.
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
13 The GNU MPFR Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
20 http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #include "mpfr-impl.h"
25 int
26 mpfr_ui_pow_ui (mpfr_ptr x, unsigned long int y, unsigned long int n,
27 mpfr_rnd_t rnd)
29 mpfr_exp_t err;
30 unsigned long m;
31 mpfr_t res;
32 mpfr_prec_t prec;
33 int size_n;
34 int inexact;
35 MPFR_ZIV_DECL (loop);
36 MPFR_SAVE_EXPO_DECL (expo);
38 if (MPFR_UNLIKELY (n <= 1))
40 if (n == 1)
41 return mpfr_set_ui (x, y, rnd); /* y^1 = y */
42 else
43 return mpfr_set_ui (x, 1, rnd); /* y^0 = 1 for any y */
45 else if (MPFR_UNLIKELY (y <= 1))
47 if (y == 1)
48 return mpfr_set_ui (x, 1, rnd); /* 1^n = 1 for any n > 0 */
49 else
50 return mpfr_set_ui (x, 0, rnd); /* 0^n = 0 for any n > 0 */
53 for (size_n = 0, m = n; m; size_n++, m >>= 1);
55 MPFR_SAVE_EXPO_MARK (expo);
56 prec = MPFR_PREC (x) + 3 + size_n;
57 mpfr_init2 (res, prec);
59 MPFR_ZIV_INIT (loop, prec);
60 for (;;)
62 int i = size_n;
64 inexact = mpfr_set_ui (res, y, MPFR_RNDU);
65 err = 1;
66 /* now 2^(i-1) <= n < 2^i: i=1+floor(log2(n)) */
67 for (i -= 2; i >= 0; i--)
69 inexact |= mpfr_mul (res, res, res, MPFR_RNDU);
70 err++;
71 if (n & (1UL << i))
72 inexact |= mpfr_mul_ui (res, res, y, MPFR_RNDU);
74 /* since the loop is executed floor(log2(n)) times,
75 we have err = 1+floor(log2(n)).
76 Since prec >= MPFR_PREC(x) + 4 + floor(log2(n)), prec > err */
77 err = prec - err;
79 if (MPFR_LIKELY (inexact == 0
80 || MPFR_CAN_ROUND (res, err, MPFR_PREC (x), rnd)))
81 break;
83 /* Actualisation of the precision */
84 MPFR_ZIV_NEXT (loop, prec);
85 mpfr_set_prec (res, prec);
87 MPFR_ZIV_FREE (loop);
89 inexact = mpfr_set (x, res, rnd);
91 mpfr_clear (res);
93 MPFR_SAVE_EXPO_FREE (expo);
94 return mpfr_check_range (x, inexact, rnd);