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