poidev.c 1.37 KB
Newer Older
Wei Chengliang's avatar
Wei Chengliang committed
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
#include <math.h>
#define PI 3.141592654

float poidev(float xm, int *idum)
{
	float gammln(float xx);
	float ran1(int *idum);
	static float sq,alxm,g,oldm=(-1.0);
	float em,t,y;

	if (xm < 12.0) {
		if (xm != oldm) {
			oldm=xm;
			g=exp(-xm);
		}
		em = -1;
		t=1.0;
		do {
			++em;
			t *= ran1(idum);
		} while (t > g);
	} else {
		if (xm != oldm) {
			oldm=xm;
			sq=sqrt(2.0*xm);
			alxm=log(xm);
			g=xm*alxm-gammln(xm+1.0);
		}
		do {
			do {
				y=tan(PI*ran1(idum));
				em=sq*y+xm;
			} while (em < 0.0);
			em=floor(em);
			t=0.9*(1.0+y*y)*exp(em*alxm-gammln(em+1.0)-g);
		} while (ran1(idum) > t);
	}
	return em;
}

float poidev_copy(float xm, int *idum)
{
	float gammln(float xx);
	float ran1_copy(int *idum);
	static float sq1,alxm1,g1,oldm1=(-1.0);
	float em,t,y;

	if (xm < 12.0) {
		if (xm != oldm1) {
			oldm1=xm;
			g1=exp(-xm);
		}
		em = -1;
		t=1.0;
		do {
			++em;
			t *= ran1_copy(idum);
		} while (t > g1);
	} else {
		if (xm != oldm1) {
			oldm1=xm;
			sq1=sqrt(2.0*xm);
			alxm1=log(xm);
			g1=xm*alxm1-gammln(xm+1.0);
		}
		do {
			do {
				y=tan(PI*ran1_copy(idum));
				em=sq1*y+xm;
			} while (em < 0.0);
			em=floor(em);
			t=0.9*(1.0+y*y)*exp(em*alxm1-gammln(em+1.0)-g1);
		} while (ran1_copy(idum) > t);
	}
	return em;
}

#undef PI
/* (C) Copr. 1986-92 Numerical Recipes Software )1!. */