Skip to content

Commit

Permalink
add support for cdf
Browse files Browse the repository at this point in the history
  • Loading branch information
dominictarr committed Sep 25, 2014
1 parent 060cc53 commit 468b114
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
63 changes: 63 additions & 0 deletions cdf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
var LogGamma = require('gamma').log

// The following code liberated from
// http://www.math.ucla.edu/~tom/distributions/chisq.html

function Gcf(X,A) { // Good for X>A+1
with (Math) {
var A0=0;
var B0=1;
var A1=1;
var B1=X;
var AOLD=0;
var N=0;
while (abs((A1-AOLD)/A1)>.00001) {
AOLD=A1;
N=N+1;
A0=A1+(N-A)*A0;
B0=B1+(N-A)*B0;
A1=X*A0+N*A1;
B1=X*B0+N*B1;
A0=A0/B1;
B0=B0/B1;
A1=A1/B1;
B1=1;
}
var Prob=exp(A*log(X)-X-LogGamma(A))*A1;
}
return 1-Prob
}

function Gser(X,A) { // Good for X<A+1.
with (Math) {
var T9=1/A;
var G=T9;
var I=1;
while (T9>G*.00001) {
T9=T9*X/(A+I);
G=G+T9;
I=I+1;
}
G=G*exp(A*log(X)-X-LogGamma(A));
}
return G
}

function Gammacdf(x,a) {
var GI;
if (x<=0) {
GI=0
} else if (x<a+1) {
GI=Gser(x,a)
} else {
GI=Gcf(x,a)
}
return GI
}

module.exports = function (Z, DF) {
if (DF<=0) {
throw new Error("Degrees of freedom must be positive")
}
return Gammacdf(Z/2,DF/2)
}
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ exports.pdf = function (x, k_) {
* Math.exp(-x / 2)
;
};

exports.cdf = require('./cdf')
9 changes: 9 additions & 0 deletions test/chi.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,12 @@ test('chi', function (t) {
t.equal(chi.pdf(2.3, 1.4), 0.11695769277348175);
t.end();
});

test('chi.cdf', function (t) {

t.equal(chi.cdf(2, 2), 0.6321204474030797)
t.equal(chi.cdf(1, 3), 0.19874802827905516)
t.equal(chi.cdf(200, 256), 0.00399456708950239)
t.end()

})

0 comments on commit 468b114

Please sign in to comment.