Skip to content

Commit cc377b2

Browse files
committed
Adding guard loops back to binomial and poission
1 parent e956a48 commit cc377b2

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

src/distributions/binomial.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,17 @@ impl Distribution<u64> for Binomial {
9393
// f(x) ~ 1/(1+x^2)
9494
let cauchy = Cauchy::new(0.0, 1.0);
9595
loop {
96-
// draw from the Cauchy distribution
97-
let comp_dev = rng.sample(cauchy);
98-
// shift the peak of the comparison distribution
99-
lresult = expected + sq * comp_dev;
96+
let mut comp_dev: f64;
97+
loop {
98+
// draw from the Cauchy distribution
99+
comp_dev = rng.sample(cauchy);
100+
// shift the peak of the comparison ditribution
101+
lresult = expected + sq * comp_dev;
102+
// repeat the drawing until we are in the range of possible values
103+
if lresult >= 0.0 && lresult < float_n + 1.0 {
104+
break;
105+
}
106+
}
100107

101108
// the result should be discrete
102109
lresult = lresult.floor();

src/distributions/cauchy.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ impl Cauchy {
5050
impl Distribution<f64> for Cauchy {
5151
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
5252
// sample from [0, 1)
53-
let mut x: f64 = rng.gen::<f64>();
53+
let mut x = rng.gen::<f64>();
5454
// guard against the extremely unlikely case we get the invalid 0.5
5555
while x == 0.5 {
5656
x = rng.gen::<f64>();

src/distributions/poisson.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,21 @@ impl Distribution<u64> for Poisson {
7575
// we use the Cauchy distribution as the comparison distribution
7676
// f(x) ~ 1/(1+x^2)
7777
let cauchy = Cauchy::new(0.0, 1.0);
78+
7879
loop {
79-
// draw from the Cauchy distribution
80-
let comp_dev = rng.sample(cauchy);
81-
// shift the peak of the comparison ditribution
82-
let mut result = self.sqrt_2lambda * comp_dev + self.lambda;
80+
let mut result;
81+
let mut comp_dev;
8382

83+
loop {
84+
// draw from the Cauchy distribution
85+
comp_dev = rng.sample(cauchy);
86+
// shift the peak of the comparison ditribution
87+
result = self.sqrt_2lambda * comp_dev + self.lambda;
88+
// repeat the drawing until we are in the range of possible values
89+
if result >= 0.0 {
90+
break;
91+
}
92+
}
8493
// now the result is a random variable greater than 0 with Cauchy distribution
8594
// the result should be an integer value
8695
result = result.floor();

0 commit comments

Comments
 (0)