uniform.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function UniformDistribution(a, b) {
  2. if (!(this instanceof UniformDistribution)) {
  3. return new UniformDistribution(a, b);
  4. }
  5. if (typeof a !== 'number' && a !== undefined) {
  6. throw TypeError('mean must be a number');
  7. }
  8. if (typeof b !== 'number' && b !== undefined) {
  9. throw TypeError('sd must be a number');
  10. }
  11. this._a = typeof a === 'number' ? a : 0;
  12. this._b = typeof b === 'number' ? b : 1;
  13. if (this._b <= this._a) {
  14. throw new RangeError('a must be greater than b');
  15. }
  16. this._k = 1 / (this._b - this._a);
  17. this._mean = (this._a + this._b) / 2;
  18. this._var = (this._a - this._b) * (this._a - this._b) / 12;
  19. }
  20. module.exports = UniformDistribution;
  21. UniformDistribution.prototype.pdf = function (x) {
  22. return (x < this._a || x > this._b) ? 0 : this._k;
  23. };
  24. UniformDistribution.prototype.cdf = function (x) {
  25. if (x < this._a) return 0;
  26. else if (x > this._b) return 1;
  27. else return (x - this._a) * this._k;
  28. };
  29. UniformDistribution.prototype.inv = function (p) {
  30. if (p < 0 || p > 1) return NaN;
  31. else return p * (this._b - this._a) + this._a;
  32. };
  33. UniformDistribution.prototype.median = function () {
  34. return this._mean;
  35. };
  36. UniformDistribution.prototype.mean = function () {
  37. return this._mean;
  38. };
  39. UniformDistribution.prototype.variance = function () {
  40. return this._var;
  41. };