-
Notifications
You must be signed in to change notification settings - Fork 224
/
poisson_distribution.js
47 lines (42 loc) · 1.74 KB
/
poisson_distribution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import epsilon from "./epsilon.js";
/**
* The [Poisson Distribution](http://en.wikipedia.org/wiki/Poisson_distribution)
* is a discrete probability distribution that expresses the probability
* of a given number of events occurring in a fixed interval of time
* and/or space if these events occur with a known average rate and
* independently of the time since the last event.
*
* The Poisson Distribution is characterized by the strictly positive
* mean arrival or occurrence rate, `λ`.
*
* @param {number} lambda location poisson distribution
* @returns {number[]} values of poisson distribution at that point
*/
function poissonDistribution(lambda) /*: ?number[] */ {
// Check that lambda is strictly positive
if (lambda <= 0) {
return undefined;
}
// our current place in the distribution
let x = 0;
// and we keep track of the current cumulative probability, in
// order to know when to stop calculating chances.
let cumulativeProbability = 0;
// the calculated cells to be returned
const cells = [];
let factorialX = 1;
// This algorithm iterates through each potential outcome,
// until the `cumulativeProbability` is very close to 1, at
// which point we've defined the vast majority of outcomes
do {
// a [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)
cells[x] = (Math.exp(-lambda) * Math.pow(lambda, x)) / factorialX;
cumulativeProbability += cells[x];
x++;
factorialX *= x;
// when the cumulativeProbability is nearly 1, we've calculated
// the useful range of this distribution
} while (cumulativeProbability < 1 - epsilon);
return cells;
}
export default poissonDistribution;