1/*___________________________________________________________________________________________________________*/
2
3function extendedBinTail (ebn, ebp, ebx)
4/*
5	returns the LEFT-tail probability for the extended binomial distribution
6	with ebn observations, ebp probability of success and ebx successes
7	i.e, Pr (X <= ebx | enb, ebp)
8
9*/
10{
11	if (ebp == 0)
12	{
13		return 0;
14	}
15
16	ebr = ebx$1; /* rounded to nearest integer */
17
18	currentBinCoeff = (1-ebp)^ebn; /*compute the first binomial coefficient */
19
20	binHead = 0;
21
22	for (ebk=0; ebk<=ebr; ebk=ebk+1)
23	{
24		binHead			= binHead + currentBinCoeff;
25		currentBinCoeff = currentBinCoeff * (ebn-ebk) / (ebk+1) * ebp / (1-ebp);
26	}
27
28	if (ebx <= ebn$1)
29	{
30		binHead = binHead + currentBinCoeff*(ebx-ebr);
31	}
32	else
33	{
34		binHead = binHead + (1-binHead)*(ebx-ebr)/(ebn-ebn$1);
35	}
36
37	return binHead;
38}
39
40/*----------------------------------------------------------------------------*/
41
42function computeBinTail   (m,n,p)
43/*
44n - number of trials
45m - cutoff point
46p - probability of success
47*/
48{
49	if (m==0)
50	{
51		lastBinTerm = (1-p)^n;
52		return 1-lastBinTerm;
53	}
54	if (m==n)
55	{
56		lastBinTerm = p^n;
57		return 0;
58	}
59
60	upToTerm = m;
61	if (m>n$2)
62	{
63		m 	= n-m;
64		omp	= 1-p;
65		binTail = p^n;
66		binTerm = n*omp*p^(n-1);
67		for (s=1; s<=m; s=s+1)
68		{
69			binTail = binTail + binTerm;
70			lastBinTerm = binTerm;
71			binTerm	= binTerm * (n-s) * omp / (p*(s+1));
72		}
73	}
74	else
75	{
76		omp	= 1-p;
77		binTail = omp^n;
78		binTerm = n*p*omp^(n-1);
79		for (s=1; s<=m; s=s+1)
80		{
81			binTail = binTail + binTerm;
82			lastBinTerm = binTerm;
83			binTerm	= binTerm * (n-s) * p / (omp*(s+1));
84		}
85		binTail = 1-binTail;
86	}
87
88	return binTail;
89}
90