1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.rng.sampling.distribution;
18
19 import org.apache.commons.rng.UniformRandomProvider;
20 import org.apache.commons.rng.core.source32.IntProvider;
21 import org.apache.commons.rng.sampling.RandomAssert;
22 import org.apache.commons.rng.simple.RandomSource;
23 import org.junit.Assert;
24 import org.junit.Test;
25
26
27
28
29 public class MarsagliaNormalisedGaussianSamplerTest {
30
31
32
33 @Test
34 public void testSharedStateSampler() {
35 final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
36 final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
37 final SharedStateContinuousSampler sampler1 =
38 MarsagliaNormalizedGaussianSampler.<MarsagliaNormalizedGaussianSampler>of(rng1);
39 final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
40 RandomAssert.assertProduceSameSequence(sampler1, sampler2);
41 }
42
43
44
45
46
47 @Test
48 public void testSamplePairIsRejected() {
49 final double value = 0.25;
50 final UniformRandomProvider rng = new IntProvider() {
51 private int i;
52
53 @Override
54 public int next() {
55
56 return 0;
57 }
58
59 @Override
60 public double nextDouble() {
61 i++;
62 if (i <= 2) {
63
64
65 return 1.0;
66 }
67 if (i <= 4) {
68
69
70 return 0.5;
71 }
72 return value;
73 }
74 };
75
76 final MarsagliaNormalizedGaussianSampler sampler = new MarsagliaNormalizedGaussianSampler(rng);
77
78
79 final double x = 2 * value - 1;
80 final double r2 = x * x + x * x;
81 final double expected = x * Math.sqrt(-2 * Math.log(r2) / r2);
82 Assert.assertEquals(expected, sampler.sample(), 0);
83 }
84 }