-
Notifications
You must be signed in to change notification settings - Fork 93
/
utils.c
111 lines (92 loc) · 1.84 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "utils.h"
/*
* given log(a) and log(b), return log(a + b)
*
*/
double log_sum(double log_a, double log_b)
{
double v;
if (log_a < log_b)
{
v = log_b+log(1 + exp(log_a-log_b));
}
else
{
v = log_a+log(1 + exp(log_b-log_a));
}
return(v);
}
/**
* Proc to calculate the value of the trigamma, the second
* derivative of the loggamma function. Accepts positive matrices.
* From Abromowitz and Stegun. Uses formulas 6.4.11 and 6.4.12 with
* recurrence formula 6.4.6. Each requires workspace at least 5
* times the size of X.
*
**/
double trigamma(double x)
{
double p;
int i;
x=x+6;
p=1/(x*x);
p=(((((0.075757575757576*p-0.033333333333333)*p+0.0238095238095238)
*p-0.033333333333333)*p+0.166666666666667)*p+1)/x+0.5*p;
for (i=0; i<6 ;i++)
{
x=x-1;
p=1/(x*x)+p;
}
return(p);
}
/*
* taylor approximation of first derivative of the log gamma function
*
*/
double digamma(double x)
{
double p;
x=x+6;
p=1/(x*x);
p=(((0.004166666666667*p-0.003968253986254)*p+
0.008333333333333)*p-0.083333333333333)*p;
p=p+log(x)-0.5/x-1/(x-1)-1/(x-2)-1/(x-3)-1/(x-4)-1/(x-5)-1/(x-6);
return p;
}
double log_gamma(double x)
{
double z=1/(x*x);
x=x+6;
z=(((-0.000595238095238*z+0.000793650793651)
*z-0.002777777777778)*z+0.083333333333333)/x;
z=(x-0.5)*log(x)-x+0.918938533204673+z-log(x-1)-
log(x-2)-log(x-3)-log(x-4)-log(x-5)-log(x-6);
return z;
}
/*
* make directory
*
*/
void make_directory(char* name)
{
mkdir(name, S_IRUSR|S_IWUSR|S_IXUSR);
}
/*
* argmax
*
*/
int argmax(double* x, int n)
{
int i;
double max = x[0];
int argmax = 0;
for (i = 1; i < n; i++)
{
if (x[i] > max)
{
max = x[i];
argmax = i;
}
}
return(argmax);
}