* transcode_data.h (rb_trans_elem_t): new field: from and to.
[ruby-svn.git] / missing / tgamma.c
blob5e306fbb43e9b65b0415e224d001f0930bce83cf
1 /* tgamma.c - public domain implementation of function tgamma(3m)
3 reference - Haruhiko Okumura: C-gengo niyoru saishin algorithm jiten
4 (New Algorithm handbook in C language) (Gijyutsu hyouron
5 sha, Tokyo, 1991) [in Japanese]
6 http://oku.edu.mie-u.ac.jp/~okumura/algo/
7 */
9 /***********************************************************
10 gamma.c -- Gamma function
11 ***********************************************************/
12 #include "ruby/config.h"
13 #include <math.h>
14 #include <errno.h>
16 #ifdef HAVE_LGAMMA_R
18 double tgamma(double x)
20 int sign;
21 double d;
22 if (x == 0.0) { /* Pole Error */
23 errno = ERANGE;
24 return 1/x < 0 ? -HUGE_VAL : HUGE_VAL;
26 if (x < 0) {
27 static double zero = 0.0;
28 double i, f;
29 f = modf(-x, &i);
30 if (f == 0.0) { /* Domain Error */
31 errno = EDOM;
32 return zero/zero;
35 d = lgamma_r(x, &sign);
36 return sign * exp(d);
39 #else
41 #include <errno.h>
42 #define PI 3.14159265358979324 /* $\pi$ */
43 #define LOG_2PI 1.83787706640934548 /* $\log 2\pi$ */
44 #define N 8
46 #define B0 1 /* Bernoulli numbers */
47 #define B1 (-1.0 / 2.0)
48 #define B2 ( 1.0 / 6.0)
49 #define B4 (-1.0 / 30.0)
50 #define B6 ( 1.0 / 42.0)
51 #define B8 (-1.0 / 30.0)
52 #define B10 ( 5.0 / 66.0)
53 #define B12 (-691.0 / 2730.0)
54 #define B14 ( 7.0 / 6.0)
55 #define B16 (-3617.0 / 510.0)
57 static double
58 loggamma(double x) /* the natural logarithm of the Gamma function. */
60 double v, w;
62 v = 1;
63 while (x < N) { v *= x; x++; }
64 w = 1 / (x * x);
65 return ((((((((B16 / (16 * 15)) * w + (B14 / (14 * 13))) * w
66 + (B12 / (12 * 11))) * w + (B10 / (10 * 9))) * w
67 + (B8 / ( 8 * 7))) * w + (B6 / ( 6 * 5))) * w
68 + (B4 / ( 4 * 3))) * w + (B2 / ( 2 * 1))) / x
69 + 0.5 * LOG_2PI - log(v) - x + (x - 0.5) * log(x);
72 double tgamma(double x) /* Gamma function */
74 if (x == 0.0) { /* Pole Error */
75 errno = ERANGE;
76 return 1/x < 0 ? -HUGE_VAL : HUGE_VAL;
78 if (x < 0) {
79 int sign;
80 static double zero = 0.0;
81 double i, f;
82 f = modf(-x, &i);
83 if (f == 0.0) { /* Domain Error */
84 errno = EDOM;
85 return zero/zero;
87 sign = (fmod(i, 2.0) != 0.0) ? 1 : -1;
88 return sign * PI / (sin(PI * f) * exp(loggamma(1 - x)));
90 return exp(loggamma(x));
92 #endif