binomial.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var cephes = require('cephes');
  2. function BinomialDistribution(properbility, size) {
  3. if (!(this instanceof BinomialDistribution)) {
  4. return new BinomialDistribution(properbility, size);
  5. }
  6. if (typeof properbility !== 'number') {
  7. throw TypeError('properbility must be a number');
  8. }
  9. if (typeof size !== 'number') {
  10. throw TypeError('size must be a number');
  11. }
  12. if (size <= 0.0) {
  13. throw TypeError('size must be positive');
  14. }
  15. if (properbility < 0.0 || properbility > 1) {
  16. throw TypeError('properbility must be between 0 and 1');
  17. }
  18. this._properbility = properbility;
  19. this._size = size;
  20. }
  21. module.exports = BinomialDistribution;
  22. BinomialDistribution.prototype.pdf = function (x) {
  23. var n = this._size;
  24. var p = this._properbility;
  25. // choose(n, x)
  26. var binomialCoefficent = cephes.gamma(n + 1) / (
  27. cephes.gamma(x + 1) * cephes.gamma(n - x + 1)
  28. )
  29. return binomialCoefficent * Math.pow(p, x) * Math.pow(1 - p, n - x);
  30. };
  31. BinomialDistribution.prototype.cdf = function (x) {
  32. return cephes.bdtr(x, this._size, this._properbility);
  33. };
  34. BinomialDistribution.prototype.inv = function (p) {
  35. throw new Error('Inverse CDF of binomial distribution is not implemented');
  36. };
  37. BinomialDistribution.prototype.median = function () {
  38. return Math.round(this._properbility * this._size);
  39. };
  40. BinomialDistribution.prototype.mean = function () {
  41. return this._properbility * this._size;
  42. };
  43. BinomialDistribution.prototype.variance = function () {
  44. return this._properbility * this._size * (1 - this._properbility);
  45. };