00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include "ruby/missing.h"
00012
00013
00014
00015 #include <math.h>
00016 #include <errno.h>
00017 #define PI 3.14159265358979324
00018 #define LOG_2PI 1.83787706640934548
00019 #define LOG_PI 1.14472988584940017
00020 #define N 8
00021
00022 #define B0 1
00023 #define B1 (-1.0 / 2.0)
00024 #define B2 ( 1.0 / 6.0)
00025 #define B4 (-1.0 / 30.0)
00026 #define B6 ( 1.0 / 42.0)
00027 #define B8 (-1.0 / 30.0)
00028 #define B10 ( 5.0 / 66.0)
00029 #define B12 (-691.0 / 2730.0)
00030 #define B14 ( 7.0 / 6.0)
00031 #define B16 (-3617.0 / 510.0)
00032
00033 static double
00034 loggamma(double x)
00035 {
00036 double v, w;
00037
00038 if (x == 1.0 || x == 2.0) return 0.0;
00039
00040 v = 1;
00041 while (x < N) { v *= x; x++; }
00042 w = 1 / (x * x);
00043 return ((((((((B16 / (16 * 15)) * w + (B14 / (14 * 13))) * w
00044 + (B12 / (12 * 11))) * w + (B10 / (10 * 9))) * w
00045 + (B8 / ( 8 * 7))) * w + (B6 / ( 6 * 5))) * w
00046 + (B4 / ( 4 * 3))) * w + (B2 / ( 2 * 1))) / x
00047 + 0.5 * LOG_2PI - log(v) - x + (x - 0.5) * log(x);
00048 }
00049
00050
00051 #ifdef __MINGW_ATTRIB_PURE
00052
00053 #define modf(_X, _Y) __extension__ ({\
00054 double intpart_modf_bug = intpart_modf_bug;\
00055 double result_modf_bug = modf((_X), &intpart_modf_bug);\
00056 *(_Y) = intpart_modf_bug;\
00057 result_modf_bug;\
00058 })
00059 #endif
00060
00061
00062 double
00063 lgamma_r(double x, int *signp)
00064 {
00065 if (x <= 0) {
00066 double i, f, s;
00067 f = modf(-x, &i);
00068 if (f == 0.0) {
00069 *signp = 1;
00070 errno = ERANGE;
00071 return HUGE_VAL;
00072 }
00073 *signp = (fmod(i, 2.0) != 0.0) ? 1 : -1;
00074 s = sin(PI * f);
00075 if (s < 0) s = -s;
00076 return LOG_PI - log(s) - loggamma(1 - x);
00077 }
00078 *signp = 1;
00079 return loggamma(x);
00080 }
00081