normal.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var cephes = require('cephes');
  2. function NormalDistribution(mean, sd) {
  3. if (!(this instanceof NormalDistribution)) {
  4. return new NormalDistribution(mean, sd);
  5. }
  6. if (typeof mean !== 'number' && mean !== undefined) {
  7. throw TypeError('mean must be a number');
  8. }
  9. if (typeof sd !== 'number' && sd !== undefined) {
  10. throw TypeError('sd must be a number');
  11. }
  12. if (sd !== undefined && sd <= 0.0) {
  13. throw TypeError('sd must be positive');
  14. }
  15. this._mean = mean || 0;
  16. this._sd = sd || 1;
  17. this._var = this._sd * this._sd;
  18. }
  19. module.exports = NormalDistribution;
  20. // -0.5 * log(2 Pi)
  21. var HALF_TWO_PI_LOG = -0.91893853320467274180;
  22. NormalDistribution.prototype.pdf = function (x) {
  23. return Math.exp(HALF_TWO_PI_LOG - Math.log(this._sd) - Math.pow(x - this._mean, 2) / (2 * this._var));
  24. };
  25. NormalDistribution.prototype.cdf = function (x) {
  26. return cephes.ndtr((x - this._mean) / this._sd);
  27. };
  28. NormalDistribution.prototype.inv = function (p) {
  29. if (p <= 0) return -Infinity;
  30. if (p >= 1) return Infinity;
  31. return this._sd * cephes.ndtri(p) + this._mean;
  32. };
  33. NormalDistribution.prototype.median = function () {
  34. return this._mean;
  35. };
  36. NormalDistribution.prototype.mean = function () {
  37. return this._mean;
  38. };
  39. NormalDistribution.prototype.variance = function () {
  40. return this._var;
  41. };