digamma.c revision 1.1.1.4
1/* mpfr_digamma -- digamma function of a floating-point number
2
3Copyright 2009-2020 Free Software Foundation, Inc.
4Contributed by the AriC and Caramba 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
20https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
2151 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
22
23#include "mpfr-impl.h"
24
25/* FIXME: Check that MPFR_GET_EXP can only be called on regular values
26   (in r14025, this is not the case) and that there cannot be integer
27   overflows. */
28
29/* Put in s an approximation of digamma(x).
30   Assumes x >= 2.
31   Assumes s does not overlap with x.
32   Returns an integer e such that the error is bounded by 2^e ulps
33   of the result s.
34*/
35static mpfr_exp_t
36mpfr_digamma_approx (mpfr_ptr s, mpfr_srcptr x)
37{
38  mpfr_prec_t p = MPFR_PREC (s);
39  mpfr_t t, u, invxx;
40  mpfr_exp_t e, exps, f, expu;
41  unsigned long n;
42
43  MPFR_ASSERTN (MPFR_IS_POS (x) && MPFR_GET_EXP (x) >= 2);
44
45  mpfr_init2 (t, p);
46  mpfr_init2 (u, p);
47  mpfr_init2 (invxx, p);
48
49  mpfr_log (s, x, MPFR_RNDN);         /* error <= 1/2 ulp */
50  mpfr_ui_div (t, 1, x, MPFR_RNDN);   /* error <= 1/2 ulp */
51  mpfr_div_2ui (t, t, 1, MPFR_RNDN); /* exact */
52  mpfr_sub (s, s, t, MPFR_RNDN);
53  /* error <= 1/2 + 1/2*2^(EXP(olds)-EXP(s)) + 1/2*2^(EXP(t)-EXP(s)).
54     For x >= 2, log(x) >= 2*(1/(2x)), thus olds >= 2t, and olds - t >= olds/2,
55     thus 0 <= EXP(olds)-EXP(s) <= 1, and EXP(t)-EXP(s) <= 0, thus
56     error <= 1/2 + 1/2*2 + 1/2 <= 2 ulps. */
57  e = 2; /* initial error */
58  mpfr_sqr (invxx, x, MPFR_RNDZ);     /* invxx = x^2 * (1 + theta)
59                                         for |theta| <= 2^(-p) */
60  mpfr_ui_div (invxx, 1, invxx, MPFR_RNDU); /* invxx = 1/x^2 * (1 + theta)^2 */
61
62  /* in the following we note err=xxx when the ratio between the approximation
63     and the exact result can be written (1 + theta)^xxx for |theta| <= 2^(-p),
64     following Higham's method */
65  mpfr_set_ui (t, 1, MPFR_RNDN); /* err = 0 */
66  for (n = 1;; n++)
67    {
68      /* The main term is Bernoulli[2n]/(2n)/x^(2n) = B[n]/(2n+1)!(2n)/x^(2n)
69         = B[n]*t[n]/(2n) where t[n]/t[n-1] = 1/(2n)/(2n+1)/x^2. */
70      mpfr_mul (t, t, invxx, MPFR_RNDU);        /* err = err + 3 */
71      mpfr_div_ui (t, t, 2 * n, MPFR_RNDU);     /* err = err + 1 */
72      mpfr_div_ui (t, t, 2 * n + 1, MPFR_RNDU); /* err = err + 1 */
73      /* we thus have err = 5n here */
74      mpfr_div_ui (u, t, 2 * n, MPFR_RNDU);     /* err = 5n+1 */
75      mpfr_mul_z (u, u, mpfr_bernoulli_cache(n), MPFR_RNDU);/* err = 5n+2, and the
76                                                   absolute error is bounded
77                                                   by 10n+4 ulp(u) [Rule 11] */
78      /* if the terms 'u' are decreasing by a factor two at least,
79         then the error coming from those is bounded by
80         sum((10n+4)/2^n, n=1..infinity) = 24 */
81      exps = MPFR_GET_EXP (s);
82      expu = MPFR_GET_EXP (u);
83      if (expu < exps - (mpfr_exp_t) p)
84        break;
85      mpfr_sub (s, s, u, MPFR_RNDN); /* error <= 24 + n/2 */
86      if (MPFR_GET_EXP (s) < exps)
87        e <<= exps - MPFR_GET_EXP (s);
88      e ++; /* error in mpfr_sub */
89      f = 10 * n + 4;
90      while (expu < exps)
91        {
92          f = (1 + f) / 2;
93          expu ++;
94        }
95      e += f; /* total rounding error coming from 'u' term */
96    }
97
98  mpfr_clear (t);
99  mpfr_clear (u);
100  mpfr_clear (invxx);
101
102  f = 0;
103  while (e > 1)
104    {
105      f++;
106      e = (e + 1) / 2;
107      /* Invariant: 2^f * e does not decrease */
108    }
109  return f;
110}
111
112/* Use the reflection formula Digamma(1-x) = Digamma(x) + Pi * cot(Pi*x),
113   i.e., Digamma(x) = Digamma(1-x) - Pi * cot(Pi*x).
114   Assume x < 1/2. */
115static int
116mpfr_digamma_reflection (mpfr_ptr y, mpfr_srcptr x, mpfr_rnd_t rnd_mode)
117{
118  mpfr_prec_t p = MPFR_PREC(y) + 10;
119  mpfr_t t, u, v;
120  mpfr_exp_t e1, expv, expx, q;
121  int inex;
122  MPFR_ZIV_DECL (loop);
123
124  MPFR_LOG_FUNC
125    (("x[%Pu]=%.*Rg rnd=%d", mpfr_get_prec(x), mpfr_log_prec, x, rnd_mode),
126     ("y[%Pu]=%.*Rg inexact=%d", mpfr_get_prec(y), mpfr_log_prec, y, inex));
127
128  /* we want that 1-x is exact with precision q: if 0 < x < 1/2, then
129     q = PREC(x)-EXP(x) is ok, otherwise if -1 <= x < 0, q = PREC(x)-EXP(x)
130     is ok, otherwise for x < -1, PREC(x) is ok if EXP(x) <= PREC(x),
131     otherwise we need EXP(x) */
132  expx = MPFR_GET_EXP (x);
133  if (expx < 0)
134    q = MPFR_PREC(x) + 1 - expx;
135  else if (expx <= MPFR_PREC(x))
136    q = MPFR_PREC(x) + 1;
137  else
138    q = expx;
139  MPFR_ASSERTN (q <= MPFR_PREC_MAX);
140  mpfr_init2 (u, q);
141  MPFR_DBGRES(inex = mpfr_ui_sub (u, 1, x, MPFR_RNDN));
142  MPFR_ASSERTN(inex == 0);
143
144  /* if x is half an integer, cot(Pi*x) = 0, thus Digamma(x) = Digamma(1-x) */
145  mpfr_mul_2ui (u, u, 1, MPFR_RNDN);
146  inex = mpfr_integer_p (u);
147  mpfr_div_2ui (u, u, 1, MPFR_RNDN);
148  if (inex)
149    {
150      inex = mpfr_digamma (y, u, rnd_mode);
151      goto end;
152    }
153
154  mpfr_init2 (t, p);
155  mpfr_init2 (v, p);
156
157  MPFR_ZIV_INIT (loop, p);
158  for (;;)
159    {
160      mpfr_const_pi (v, MPFR_RNDN);  /* v = Pi*(1+theta) for |theta|<=2^(-p) */
161      mpfr_mul (t, v, x, MPFR_RNDN); /* (1+theta)^2 */
162      e1 = MPFR_GET_EXP(t) - (mpfr_exp_t) p + 1; /* bound for t: err(t) <= 2^e1 */
163      mpfr_cot (t, t, MPFR_RNDN);
164      /* cot(t * (1+h)) = cot(t) - theta * (1 + cot(t)^2) with |theta|<=t*h */
165      if (MPFR_GET_EXP(t) > 0)
166        e1 = e1 + 2 * MPFR_EXP(t) + 1;
167      else
168        e1 = e1 + 1;
169      /* now theta * (1 + cot(t)^2) <= 2^e1 */
170      e1 += (mpfr_exp_t) p - MPFR_EXP(t); /* error is now 2^e1 ulps */
171      mpfr_mul (t, t, v, MPFR_RNDN);
172      e1 ++;
173      mpfr_digamma (v, u, MPFR_RNDN);   /* error <= 1/2 ulp */
174      expv = MPFR_GET_EXP (v);
175      mpfr_sub (v, v, t, MPFR_RNDN);
176      if (MPFR_GET_EXP (v) < MPFR_GET_EXP (t))
177        e1 += MPFR_EXP(t) - MPFR_EXP(v); /* scale error for t wrt new v */
178      /* now take into account the 1/2 ulp error for v */
179      if (expv - MPFR_EXP(v) - 1 > e1)
180        e1 = expv - MPFR_EXP(v) - 1;
181      else
182        e1 ++;
183      e1 ++; /* rounding error for mpfr_sub */
184      if (MPFR_CAN_ROUND (v, p - e1, MPFR_PREC(y), rnd_mode))
185        break;
186      MPFR_ZIV_NEXT (loop, p);
187      mpfr_set_prec (t, p);
188      mpfr_set_prec (v, p);
189    }
190  MPFR_ZIV_FREE (loop);
191
192  inex = mpfr_set (y, v, rnd_mode);
193
194  mpfr_clear (t);
195  mpfr_clear (v);
196 end:
197  mpfr_clear (u);
198
199  return inex;
200}
201
202/* we have x >= 1/2 here */
203static int
204mpfr_digamma_positive (mpfr_ptr y, mpfr_srcptr x, mpfr_rnd_t rnd_mode)
205{
206  mpfr_prec_t p = MPFR_PREC(y) + 10, q;
207  mpfr_t t, u, x_plus_j;
208  int inex;
209  mpfr_exp_t errt, erru, expt;
210  unsigned long j = 0, min;
211  MPFR_ZIV_DECL (loop);
212
213  MPFR_LOG_FUNC
214    (("x[%Pu]=%.*Rg rnd=%d", mpfr_get_prec(x), mpfr_log_prec, x, rnd_mode),
215     ("y[%Pu]=%.*Rg inexact=%d", mpfr_get_prec(y), mpfr_log_prec, y, inex));
216
217  /* compute a precision q such that x+1 is exact */
218  if (MPFR_PREC(x) < MPFR_GET_EXP(x))
219    q = MPFR_EXP(x);
220  else
221    q = MPFR_PREC(x) + 1;
222
223  /* for very large x, use |digamma(x) - log(x)| < 1/x < 2^(1-EXP(x)) */
224  if (MPFR_PREC(y) + 10 < MPFR_EXP(x))
225    {
226      /* this ensures EXP(x) >= 3, thus x >= 4, thus log(x) > 1 */
227      mpfr_init2 (t, MPFR_PREC(y) + 10);
228      mpfr_log (t, x, MPFR_RNDZ);
229      if (MPFR_CAN_ROUND (t, MPFR_PREC(y) + 10, MPFR_PREC(y), rnd_mode))
230        {
231          inex = mpfr_set (y, t, rnd_mode);
232          mpfr_clear (t);
233          return inex;
234        }
235      mpfr_clear (t);
236    }
237
238  mpfr_init2 (x_plus_j, q);
239
240  mpfr_init2 (t, p);
241  mpfr_init2 (u, p);
242  MPFR_ZIV_INIT (loop, p);
243  for(;;)
244    {
245      /* Lower bound for x+j in mpfr_digamma_approx call: since the smallest
246         term of the divergent series for Digamma(x) is about exp(-2*Pi*x), and
247         we want it to be less than 2^(-p), this gives x > p*log(2)/(2*Pi)
248         i.e., x >= 0.1103 p.
249         To be safe, we ensure x >= 0.25 * p.
250      */
251      min = (p + 3) / 4;
252      if (min < 2)
253        min = 2;
254
255      mpfr_set (x_plus_j, x, MPFR_RNDN);
256      mpfr_set_ui (u, 0, MPFR_RNDN);
257      j = 0;
258      while (mpfr_cmp_ui (x_plus_j, min) < 0)
259        {
260          j ++;
261          mpfr_ui_div (t, 1, x_plus_j, MPFR_RNDN); /* err <= 1/2 ulp */
262          mpfr_add (u, u, t, MPFR_RNDN);
263          inex = mpfr_add_ui (x_plus_j, x_plus_j, 1, MPFR_RNDZ);
264          if (inex != 0) /* we lost one bit */
265            {
266              q ++;
267              mpfr_prec_round (x_plus_j, q, MPFR_RNDZ);
268              mpfr_nextabove (x_plus_j);
269            }
270          /* since all terms are positive, the error is bounded by j ulps */
271        }
272      for (erru = 0; j > 1; erru++, j = (j + 1) / 2);
273      errt = mpfr_digamma_approx (t, x_plus_j);
274      expt = MPFR_GET_EXP (t);
275      mpfr_sub (t, t, u, MPFR_RNDN);
276      if (MPFR_GET_EXP (t) < expt)
277        errt += expt - MPFR_EXP(t);
278      /* Warning: if u is zero (which happens when x_plus_j >= min at the
279         beginning of the while loop above), EXP(u) is not defined.
280         In this case we have no error from u. */
281      if (MPFR_NOTZERO(u) && MPFR_GET_EXP (t) < MPFR_GET_EXP (u))
282        erru += MPFR_EXP(u) - MPFR_EXP(t);
283      if (errt > erru)
284        errt = errt + 1;
285      else if (errt == erru)
286        errt = errt + 2;
287      else
288        errt = erru + 1;
289      if (MPFR_CAN_ROUND (t, p - errt, MPFR_PREC(y), rnd_mode))
290        break;
291      MPFR_ZIV_NEXT (loop, p);
292      mpfr_set_prec (t, p);
293      mpfr_set_prec (u, p);
294    }
295  MPFR_ZIV_FREE (loop);
296  inex = mpfr_set (y, t, rnd_mode);
297  mpfr_clear (t);
298  mpfr_clear (u);
299  mpfr_clear (x_plus_j);
300  return inex;
301}
302
303int
304mpfr_digamma (mpfr_ptr y, mpfr_srcptr x, mpfr_rnd_t rnd_mode)
305{
306  int inex;
307  MPFR_SAVE_EXPO_DECL (expo);
308
309  MPFR_LOG_FUNC
310    (("x[%Pu]=%.*Rg rnd=%d", mpfr_get_prec(x), mpfr_log_prec, x, rnd_mode),
311     ("y[%Pu]=%.*Rg inexact=%d", mpfr_get_prec(y), mpfr_log_prec, y, inex));
312
313  if (MPFR_UNLIKELY(MPFR_IS_SINGULAR(x)))
314    {
315      if (MPFR_IS_NAN(x))
316        {
317          MPFR_SET_NAN(y);
318          MPFR_RET_NAN;
319        }
320      else if (MPFR_IS_INF(x))
321        {
322          if (MPFR_IS_POS(x)) /* Digamma(+Inf) = +Inf */
323            {
324              MPFR_SET_SAME_SIGN(y, x);
325              MPFR_SET_INF(y);
326              MPFR_RET(0);
327            }
328          else                /* Digamma(-Inf) = NaN */
329            {
330              MPFR_SET_NAN(y);
331              MPFR_RET_NAN;
332            }
333        }
334      else /* Zero case */
335        {
336          /* the following works also in case of overlap */
337          MPFR_SET_INF(y);
338          MPFR_SET_OPPOSITE_SIGN(y, x);
339          MPFR_SET_DIVBY0 ();
340          MPFR_RET(0);
341        }
342    }
343
344  /* Digamma is undefined for negative integers */
345  if (MPFR_IS_NEG(x) && mpfr_integer_p (x))
346    {
347      MPFR_SET_NAN(y);
348      MPFR_RET_NAN;
349    }
350
351  /* now x is a normal number */
352
353  MPFR_SAVE_EXPO_MARK (expo);
354  /* for x very small, we have Digamma(x) = -1/x - gamma + O(x), more precisely
355     -1 < Digamma(x) + 1/x < 0 for -0.2 < x < 0.2, thus:
356     (i) either x is a power of two, then 1/x is exactly representable, and
357         as long as 1/2*ulp(1/x) > 1, we can conclude;
358     (ii) otherwise assume x has <= n bits, and y has <= n+1 bits, then
359   |y + 1/x| >= 2^(-2n) ufp(y), where ufp means unit in first place.
360   Since |Digamma(x) + 1/x| <= 1, if 2^(-2n) ufp(y) >= 2, then
361   |y - Digamma(x)| >= 2^(-2n-1)ufp(y), and rounding -1/x gives the correct result.
362   If x < 2^E, then y > 2^(-E), thus ufp(y) > 2^(-E-1).
363   A sufficient condition is thus EXP(x) <= -2 MAX(PREC(x),PREC(Y)). */
364  if (MPFR_GET_EXP (x) < -2)
365    {
366      if (MPFR_EXP(x) <= -2 * (mpfr_exp_t) MAX(MPFR_PREC(x), MPFR_PREC(y)))
367        {
368          int signx = MPFR_SIGN(x);
369          inex = mpfr_si_div (y, -1, x, rnd_mode);
370          if (inex == 0) /* x is a power of two */
371            { /* result always -1/x, except when rounding down */
372              if (rnd_mode == MPFR_RNDA)
373                rnd_mode = (signx > 0) ? MPFR_RNDD : MPFR_RNDU;
374              if (rnd_mode == MPFR_RNDZ)
375                rnd_mode = (signx > 0) ? MPFR_RNDU : MPFR_RNDD;
376              if (rnd_mode == MPFR_RNDU)
377                inex = 1;
378              else if (rnd_mode == MPFR_RNDD)
379                {
380                  mpfr_nextbelow (y);
381                  inex = -1;
382                }
383              else /* nearest */
384                inex = 1;
385            }
386          MPFR_SAVE_EXPO_UPDATE_FLAGS (expo, __gmpfr_flags);
387          goto end;
388        }
389    }
390
391  if (MPFR_IS_NEG(x))
392    inex = mpfr_digamma_reflection (y, x, rnd_mode);
393  /* if x < 1/2 we use the reflection formula */
394  else if (MPFR_EXP(x) < 0)
395    inex = mpfr_digamma_reflection (y, x, rnd_mode);
396  else
397    inex = mpfr_digamma_positive (y, x, rnd_mode);
398
399 end:
400  MPFR_SAVE_EXPO_FREE (expo);
401  return mpfr_check_range (y, inex, rnd_mode);
402}
403