1 package org.lcsim.math.distribution;
2
3 import java.util.Random;
4
5
6
7
8
9
10
11
12
13
14 public class EmpiricalDistribution
15 {
16 private Random _rand;
17 protected double[] _cdf;
18 protected int _interpolationType;
19
20
21
22
23
24
25
26
27
28
29 public EmpiricalDistribution(double[] pdf)
30 {
31 _rand = new Random();
32 setState(pdf);
33 }
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public void setSeed(long seed)
48 {
49 _rand.setSeed(seed);
50 }
51
52
53
54
55
56 public double nextDouble()
57 {
58 double rand = _rand.nextDouble();
59 if (this._cdf == null)
60 {
61 return rand;
62 }
63
64 int nBins = _cdf.length - 1;
65 int nbelow = 0;
66 int nabove = nBins;
67
68 while (nabove > nbelow + 1)
69 {
70 int middle = (nabove + nbelow + 1) >> 1;
71 if (rand >= _cdf[middle])
72 {
73 nbelow = middle;
74 } else
75 {
76 nabove = middle;
77 }
78 }
79
80 double binMeasure = _cdf[nabove] - _cdf[nbelow];
81 if (binMeasure == 0.0)
82 {
83
84
85
86
87 return (nbelow + 0.5) / nBins;
88 }
89 double binFraction = (rand - _cdf[nbelow]) / binMeasure;
90 return (nbelow + binFraction) / nBins;
91 }
92
93
94
95
96 public double pdf(int k)
97 {
98 if (k < 0 || k >= _cdf.length - 1)
99 {
100 return 0.0;
101 }
102 return _cdf[k] - _cdf[k - 1];
103 }
104
105
106
107
108 public void setState(double[] pdf)
109 {
110 if (pdf == null || pdf.length == 0)
111 {
112 this._cdf = null;
113
114 return;
115 }
116
117
118 int nBins = pdf.length;
119 this._cdf = new double[nBins + 1];
120
121 _cdf[0] = 0;
122 for (int ptn = 0; ptn < nBins; ++ptn)
123 {
124 double prob = pdf[ptn];
125 if (prob < 0.0)
126 {
127 throw new IllegalArgumentException("Negative probability");
128 }
129 _cdf[ptn + 1] = _cdf[ptn] + prob;
130 }
131 if (_cdf[nBins] <= 0.0)
132 {
133 throw new IllegalArgumentException("At least one probability must be > 0.0");
134 }
135
136 for (int ptn = 0; ptn < nBins + 1; ++ptn)
137 {
138 _cdf[ptn] /= _cdf[nBins];
139 }
140
141 }
142
143
144
145
146 public String toString()
147 {
148 return this.getClass().getName();
149 }
150 }