1/* mpfr_agm -- arithmetic-geometric mean of two floating-point numbers
2
3Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4Contributed by the Arenaire and Cacao projects, INRIA.
5
6This file is part of the GNU MPFR Library.
7
8The GNU MPFR Library is free software; you can redistribute it and/or modify
9it under the terms of the GNU Lesser General Public License as published by
10the Free Software Foundation; either version 3 of the License, or (at your
11option) any later version.
12
13The GNU MPFR Library is distributed in the hope that it will be useful, but
14WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16License for more details.
17
18You should have received a copy of the GNU Lesser General Public License
19along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
20http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
2151 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
22
23#define MPFR_NEED_LONGLONG_H
24#include "mpfr-impl.h"
25
26/* agm(x,y) is between x and y, so we don't need to save exponent range */
27int
28mpfr_agm (mpfr_ptr r, mpfr_srcptr op2, mpfr_srcptr op1, mpfr_rnd_t rnd_mode)
29{
30  int compare, inexact;
31  mp_size_t s;
32  mpfr_prec_t p, q;
33  mp_limb_t *up, *vp, *ufp, *vfp;
34  mpfr_t u, v, uf, vf, sc1, sc2;
35  mpfr_exp_t scaleop = 0, scaleit;
36  unsigned long n; /* number of iterations */
37  MPFR_ZIV_DECL (loop);
38  MPFR_TMP_DECL(marker);
39  MPFR_SAVE_EXPO_DECL (expo);
40
41  MPFR_LOG_FUNC (("op2[%#R]=%R op1[%#R]=%R rnd=%d", op2,op2,op1,op1,rnd_mode),
42                 ("r[%#R]=%R inexact=%d", r, r, inexact));
43
44  /* Deal with special values */
45  if (MPFR_ARE_SINGULAR (op1, op2))
46    {
47      /* If a or b is NaN, the result is NaN */
48      if (MPFR_IS_NAN(op1) || MPFR_IS_NAN(op2))
49        {
50          MPFR_SET_NAN(r);
51          MPFR_RET_NAN;
52        }
53      /* now one of a or b is Inf or 0 */
54      /* If a and b is +Inf, the result is +Inf.
55         Otherwise if a or b is -Inf or 0, the result is NaN */
56      else if (MPFR_IS_INF(op1) || MPFR_IS_INF(op2))
57        {
58          if (MPFR_IS_STRICTPOS(op1) && MPFR_IS_STRICTPOS(op2))
59            {
60              MPFR_SET_INF(r);
61              MPFR_SET_SAME_SIGN(r, op1);
62              MPFR_RET(0); /* exact */
63            }
64          else
65            {
66              MPFR_SET_NAN(r);
67              MPFR_RET_NAN;
68            }
69        }
70      else /* a and b are neither NaN nor Inf, and one is zero */
71        {  /* If a or b is 0, the result is +0 since a sqrt is positive */
72          MPFR_ASSERTD (MPFR_IS_ZERO (op1) || MPFR_IS_ZERO (op2));
73          MPFR_SET_POS (r);
74          MPFR_SET_ZERO (r);
75          MPFR_RET (0); /* exact */
76        }
77    }
78
79  /* If a or b is negative (excluding -Infinity), the result is NaN */
80  if (MPFR_UNLIKELY(MPFR_IS_NEG(op1) || MPFR_IS_NEG(op2)))
81    {
82      MPFR_SET_NAN(r);
83      MPFR_RET_NAN;
84    }
85
86  /* Precision of the following calculus */
87  q = MPFR_PREC(r);
88  p = q + MPFR_INT_CEIL_LOG2(q) + 15;
89  MPFR_ASSERTD (p >= 7); /* see algorithms.tex */
90  s = (p - 1) / GMP_NUMB_BITS + 1;
91
92  /* b (op2) and a (op1) are the 2 operands but we want b >= a */
93  compare = mpfr_cmp (op1, op2);
94  if (MPFR_UNLIKELY( compare == 0 ))
95    {
96      mpfr_set (r, op1, rnd_mode);
97      MPFR_RET (0); /* exact */
98    }
99  else if (compare > 0)
100    {
101      mpfr_srcptr t = op1;
102      op1 = op2;
103      op2 = t;
104    }
105
106  /* Now b (=op2) > a (=op1) */
107
108  MPFR_SAVE_EXPO_MARK (expo);
109
110  MPFR_TMP_MARK(marker);
111
112  /* Main loop */
113  MPFR_ZIV_INIT (loop, p);
114  for (;;)
115    {
116      mpfr_prec_t eq;
117      unsigned long err = 0;  /* must be set to 0 at each Ziv iteration */
118      MPFR_BLOCK_DECL (flags);
119
120      /* Init temporary vars */
121      MPFR_TMP_INIT (up, u, p, s);
122      MPFR_TMP_INIT (vp, v, p, s);
123      MPFR_TMP_INIT (ufp, uf, p, s);
124      MPFR_TMP_INIT (vfp, vf, p, s);
125
126      /* Calculus of un and vn */
127    retry:
128      MPFR_BLOCK (flags,
129                  mpfr_mul (u, op1, op2, MPFR_RNDN);
130                  /* mpfr_mul(...): faster since PREC(op) < PREC(u) */
131                  mpfr_add (v, op1, op2, MPFR_RNDN);
132                  /* mpfr_add with !=prec is still good */);
133      if (MPFR_UNLIKELY (MPFR_OVERFLOW (flags) || MPFR_UNDERFLOW (flags)))
134        {
135          mpfr_exp_t e1 , e2;
136
137          MPFR_ASSERTN (scaleop == 0);
138          e1 = MPFR_GET_EXP (op1);
139          e2 = MPFR_GET_EXP (op2);
140
141          /* Let's determine scaleop to avoid an overflow/underflow. */
142          if (MPFR_OVERFLOW (flags))
143            {
144              /* Let's recall that emin <= e1 <= e2 <= emax.
145                 There has been an overflow. Thus e2 >= emax/2.
146                 If the mpfr_mul overflowed, then e1 + e2 > emax.
147                 If the mpfr_add overflowed, then e2 = emax.
148                 We want: (e1 + scale) + (e2 + scale) <= emax,
149                 i.e. scale <= (emax - e1 - e2) / 2. Let's take
150                 scale = min(floor((emax - e1 - e2) / 2), -1).
151                 This is OK, as:
152                 1. emin <= scale <= -1.
153                 2. e1 + scale >= emin. Indeed:
154                    * If e1 + e2 > emax, then
155                      e1 + scale >= e1 + (emax - e1 - e2) / 2 - 1
156                                 >= (emax + e1 - emax) / 2 - 1
157                                 >= e1 / 2 - 1 >= emin.
158                    * Otherwise, mpfr_mul didn't overflow, therefore
159                      mpfr_add overflowed and e2 = emax, so that
160                      e1 > emin (see restriction below).
161                      e1 + scale > emin - 1, thus e1 + scale >= emin.
162                 3. e2 + scale <= emax, since scale < 0. */
163              if (e1 + e2 > __gmpfr_emax)
164                {
165                  scaleop = - (((e1 + e2) - __gmpfr_emax + 1) / 2);
166                  MPFR_ASSERTN (scaleop < 0);
167                }
168              else
169                {
170                  /* The addition necessarily overflowed. */
171                  MPFR_ASSERTN (e2 == __gmpfr_emax);
172                  /* The case where e1 = emin and e2 = emax is not supported
173                     here. This would mean that the precision of e2 would be
174                     huge (and possibly not supported in practice anyway). */
175                  MPFR_ASSERTN (e1 > __gmpfr_emin);
176                  scaleop = -1;
177                }
178
179            }
180          else  /* underflow only (in the multiplication) */
181            {
182              /* We have e1 + e2 <= emin (so, e1 <= e2 <= 0).
183                 We want: (e1 + scale) + (e2 + scale) >= emin + 1,
184                 i.e. scale >= (emin + 1 - e1 - e2) / 2. let's take
185                 scale = ceil((emin + 1 - e1 - e2) / 2). This is OK, as:
186                 1. 1 <= scale <= emax.
187                 2. e1 + scale >= emin + 1 >= emin.
188                 3. e2 + scale <= scale <= emax. */
189              MPFR_ASSERTN (e1 <= e2 && e2 <= 0);
190              scaleop = (__gmpfr_emin + 2 - e1 - e2) / 2;
191              MPFR_ASSERTN (scaleop > 0);
192            }
193
194          MPFR_ALIAS (sc1, op1, MPFR_SIGN (op1), e1 + scaleop);
195          MPFR_ALIAS (sc2, op2, MPFR_SIGN (op2), e2 + scaleop);
196          op1 = sc1;
197          op2 = sc2;
198          MPFR_LOG_MSG (("Exception in pre-iteration, scale = %"
199                         MPFR_EXP_FSPEC "d\n", scaleop));
200          goto retry;
201        }
202
203      mpfr_clear_flags ();
204      mpfr_sqrt (u, u, MPFR_RNDN);
205      mpfr_div_2ui (v, v, 1, MPFR_RNDN);
206
207      scaleit = 0;
208      n = 1;
209      while (mpfr_cmp2 (u, v, &eq) != 0 && eq <= p - 2)
210        {
211          MPFR_BLOCK_DECL (flags2);
212
213          MPFR_LOG_MSG (("Iteration n = %lu\n", n));
214
215        retry2:
216          mpfr_add (vf, u, v, MPFR_RNDN);  /* No overflow? */
217          mpfr_div_2ui (vf, vf, 1, MPFR_RNDN);
218          /* See proof in algorithms.tex */
219          if (4*eq > p)
220            {
221              mpfr_t w;
222              MPFR_BLOCK_DECL (flags3);
223
224              MPFR_LOG_MSG (("4*eq > p\n", 0));
225
226              /* vf = V(k) */
227              mpfr_init2 (w, (p + 1) / 2);
228              MPFR_BLOCK
229                (flags3,
230                 mpfr_sub (w, v, u, MPFR_RNDN);       /* e = V(k-1)-U(k-1) */
231                 mpfr_sqr (w, w, MPFR_RNDN);          /* e = e^2 */
232                 mpfr_div_2ui (w, w, 4, MPFR_RNDN);   /* e*= (1/2)^2*1/4  */
233                 mpfr_div (w, w, vf, MPFR_RNDN);      /* 1/4*e^2/V(k) */
234                 );
235              if (MPFR_LIKELY (! MPFR_UNDERFLOW (flags3)))
236                {
237                  mpfr_sub (v, vf, w, MPFR_RNDN);
238                  err = MPFR_GET_EXP (vf) - MPFR_GET_EXP (v); /* 0 or 1 */
239                  mpfr_clear (w);
240                  break;
241                }
242              /* There has been an underflow because of the cancellation
243                 between V(k-1) and U(k-1). Let's use the conventional
244                 method. */
245              MPFR_LOG_MSG (("4*eq > p -> underflow\n", 0));
246              mpfr_clear (w);
247              mpfr_clear_underflow ();
248            }
249          /* U(k) increases, so that U.V can overflow (but not underflow). */
250          MPFR_BLOCK (flags2, mpfr_mul (uf, u, v, MPFR_RNDN););
251          if (MPFR_UNLIKELY (MPFR_OVERFLOW (flags2)))
252            {
253              mpfr_exp_t scale2;
254
255              scale2 = - (((MPFR_GET_EXP (u) + MPFR_GET_EXP (v))
256                           - __gmpfr_emax + 1) / 2);
257              MPFR_EXP (u) += scale2;
258              MPFR_EXP (v) += scale2;
259              scaleit += scale2;
260              MPFR_LOG_MSG (("Overflow in iteration n = %lu, scaleit = %"
261                             MPFR_EXP_FSPEC "d (%" MPFR_EXP_FSPEC "d)\n",
262                             n, scaleit, scale2));
263              mpfr_clear_overflow ();
264              goto retry2;
265            }
266          mpfr_sqrt (u, uf, MPFR_RNDN);
267          mpfr_swap (v, vf);
268          n ++;
269        }
270
271      MPFR_LOG_MSG (("End of iterations (n = %lu)\n", n));
272
273      /* the error on v is bounded by (18n+51) ulps, or twice if there
274         was an exponent loss in the final subtraction */
275      err += MPFR_INT_CEIL_LOG2(18 * n + 51); /* 18n+51 should not overflow
276                                                 since n is about log(p) */
277      /* we should have n+2 <= 2^(p/4) [see algorithms.tex] */
278      if (MPFR_LIKELY (MPFR_INT_CEIL_LOG2(n + 2) <= p / 4 &&
279                       MPFR_CAN_ROUND (v, p - err, q, rnd_mode)))
280        break; /* Stop the loop */
281
282      /* Next iteration */
283      MPFR_ZIV_NEXT (loop, p);
284      s = (p - 1) / GMP_NUMB_BITS + 1;
285    }
286  MPFR_ZIV_FREE (loop);
287
288  if (MPFR_UNLIKELY ((__gmpfr_flags & (MPFR_FLAGS_ALL ^ MPFR_FLAGS_INEXACT))
289                     != 0))
290    {
291      MPFR_ASSERTN (! mpfr_overflow_p ());   /* since mpfr_clear_flags */
292      MPFR_ASSERTN (! mpfr_underflow_p ());  /* since mpfr_clear_flags */
293      MPFR_ASSERTN (! mpfr_nanflag_p ());    /* since mpfr_clear_flags */
294    }
295
296  /* Setting of the result */
297  inexact = mpfr_set (r, v, rnd_mode);
298  MPFR_EXP (r) -= scaleop + scaleit;
299
300  /* Let's clean */
301  MPFR_TMP_FREE(marker);
302
303  MPFR_SAVE_EXPO_FREE (expo);
304  /* From the definition of the AGM, underflow and overflow
305     are not possible. */
306  return mpfr_check_range (r, inexact, rnd_mode);
307  /* agm(u,v) can be exact for u, v rational only for u=v.
308     Proof (due to Nicolas Brisebarre): it suffices to consider
309     u=1 and v<1. Then 1/AGM(1,v) = 2F1(1/2,1/2,1;1-v^2),
310     and a theorem due to G.V. Chudnovsky states that for x a
311     non-zero algebraic number with |x|<1, then
312     2F1(1/2,1/2,1;x) and 2F1(-1/2,1/2,1;x) are algebraically
313     independent over Q. */
314}
315