org.apache.commons.rng.UniformRandomProvider Java Examples

The following examples show how to use org.apache.commons.rng.UniformRandomProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StressTestCommand.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the task.
 *
 * @param randomSource The random source.
 * @param rng RNG to be tested.
 * @param seed The seed used to create the RNG.
 * @param output Output report file.
 * @param command The sub-process command to run.
 * @param cmd The run command.
 * @param progressTracker The progress tracker.
 */
StressTestTask(RandomSource randomSource,
               UniformRandomProvider rng,
               byte[] seed,
               File output,
               List<String> command,
               StressTestCommand cmd,
               ProgressTracker progressTracker) {
    this.randomSource = randomSource;
    this.rng = rng;
    this.seed = seed;
    this.output = output;
    this.command = command;
    this.cmd = cmd;
    this.progressTracker = progressTracker;
}
 
Example #2
Source File: GaussianSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Test the SharedStateSampler implementation throws if the underlying sampler is
 * not a SharedStateSampler.
 */
@Test(expected = UnsupportedOperationException.class)
public void testSharedStateSamplerThrowsIfUnderlyingSamplerDoesNotShareState() {
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final NormalizedGaussianSampler gauss = new NormalizedGaussianSampler() {
        @Override
        public double sample() {
            return 0;
        }
    };
    final double mean = 1.23;
    final double standardDeviation = 4.56;
    final SharedStateContinuousSampler sampler1 =
        GaussianSampler.of(gauss, mean, standardDeviation);
    sampler1.withUniformRandomProvider(rng2);
}
 
Example #3
Source File: GeometricSampler.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * @param rng Generator of uniformly distributed random numbers
 * @param probabilityOfSuccess The probability of success (must be in the range
 * {@code [0 < probabilityOfSuccess < 1]})
 */
GeometricExponentialSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
    this.rng = rng;
    // Use a related exponential distribution:
    // λ = −ln(1 − probabilityOfSuccess)
    // exponential mean = 1 / λ
    // --
    // Note on validation:
    // If probabilityOfSuccess == Math.nextDown(1.0) the exponential mean is >0 (valid).
    // If probabilityOfSuccess == Double.MIN_VALUE the exponential mean is +Infinity
    // and the sample will always be Integer.MAX_VALUE (the distribution is truncated). It
    // is noted in the class Javadoc that the use of a small p leads to truncation so
    // no checks are made for this case.
    final double exponentialMean = 1.0 / (-Math.log1p(-probabilityOfSuccess));
    exponentialSampler = AhrensDieterExponentialSampler.of(rng, exponentialMean);
}
 
Example #4
Source File: BetaDistributionTest.java    From commons-statistics with Apache License 2.0 6 votes vote down vote up
@Test
void testGoodnessOfFit() {
    final UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_19937_A,
                                                          123456789L);

    final int numSamples = 1000;
    final double level = 0.01;
    for (final double alpha : ALPHA_BETAS) {
        for (final double beta : ALPHA_BETAS) {
            final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);

            final ContinuousDistribution.Sampler sampler = betaDistribution.createSampler(rng);
            final double[] observed = AbstractContinuousDistribution.sample(numSamples, sampler);

            final double gT = gTest(betaDistribution, observed);
            Assertions.assertFalse(gT < level,
                () -> "G goodness-of-fit (" + gT + ") test rejected null at alpha = " + level);
        }
    }
}
 
Example #5
Source File: QuaternionRotationTest.java    From commons-geometry with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiply_numericalStability() {
    // arrange
    int slices = 1024;
    double delta = (8.0 * PlaneAngleRadians.PI / 3.0) / slices;

    QuaternionRotation q = QuaternionRotation.identity();

    UniformRandomProvider rand = RandomSource.create(RandomSource.JDK, 2L);

    // act
    for (int i = 0; i < slices; ++i) {
        double angle = rand.nextDouble();
        QuaternionRotation forward = QuaternionRotation.fromAxisAngle(PLUS_DIAGONAL, angle);
        QuaternionRotation backward = QuaternionRotation.fromAxisAngle(PLUS_DIAGONAL, delta - angle);

        q = q.multiply(forward).multiply(backward);
    }

    // assert
    Assert.assertTrue(q.getQuaternion().getW() > 0);
    Assert.assertEquals(1.0, q.getQuaternion().norm(), EPS);

    assertRotationEquals(StandardRotations.PLUS_DIAGONAL_TWO_THIRDS_PI, q);
}
 
Example #6
Source File: ProvidersCommonParametricTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnrestorable() {
    // Create two generators of the same type as the one being tested.
    final UniformRandomProvider rng1 = RandomSource.create(originalSource, originalSeed, originalArgs);
    final UniformRandomProvider rng2 = RandomSource.unrestorable(RandomSource.create(originalSource, originalSeed, originalArgs));

    // Ensure that they generate the same values.
    RandomAssert.assertProduceSameSequence(rng1, rng2);

    // Cast must work.
    final RestorableUniformRandomProvider restorable = (RestorableUniformRandomProvider) rng1;
    // Cast must fail.
    try {
        final RestorableUniformRandomProvider dummy = (RestorableUniformRandomProvider) rng2;
        Assert.fail("Cast should have failed");
    } catch (ClassCastException e) {
        // Expected.
    }
}
 
Example #7
Source File: CStandardTest.java    From commons-numbers with Apache License 2.0 6 votes vote down vote up
/**
 * ISO C Standard G.6 (7).
 */
@Test
void testImplicitTrig() {
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
    for (int i = 0; i < 100; i++) {
        final double re = next(rng);
        final double im = next(rng);
        final Complex z = complex(re, im);
        final Complex iz = z.multiplyImaginary(1);
        assertComplex(z.asin(), iz.asinh().multiplyImaginary(-1));
        assertComplex(z.atan(), iz.atanh().multiplyImaginary(-1));
        assertComplex(z.cos(), iz.cosh());
        assertComplex(z.sin(), iz.sinh().multiplyImaginary(-1));
        assertComplex(z.tan(), iz.tanh().multiplyImaginary(-1));
    }
}
 
Example #8
Source File: ComplexTest.java    From commons-numbers with Apache License 2.0 6 votes vote down vote up
/**
 * Test the abs and log functions are consistent. The definition of log uses abs and
 * the result should be computed using the same representation of the complex number's
 * magnitude (abs). If the log function uses a simple representation
 * {@code sqrt(x^2 + y^2)} then this may have a 1 ulp or more difference from the high
 * accuracy result computed by abs. This will propagate to create differences in log.
 *
 * <p>Note: This test is separated from the similar test for sqrt to allow testing
 * different numbers.
 */
@Test
void testAbsVsLog() {
    final UniformRandomProvider rng = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP);
    // Note: All methods implement scaling to ensure the magnitude can be computed.
    // Try very large or small numbers that will over/underflow to test that the
    // scaling
    // is consistent. Note that:
    // - log will set the real component using log(|z|). This will massively reduce
    // the magnitude when |z| >> 1. Highest accuracy will be when |z| is as large
    // as possible before computing the log.

    // No test around |z| == 1 as a high accuracy computation is required:
    // Math.log1p(x*x+y*y-1)

    // Each sample fails approximately 25% of the time if using a standard x^2+y^2 in
    // log()
    // and high accuracy representation in abs(). Use 100 samples to ensure the
    // behavior is OK.
    assertAbsVsLog(100,
        () -> Complex.ofCartesian(createFixedExponentNumber(rng, 1022), createFixedExponentNumber(rng, 1022)));
    assertAbsVsLog(100,
        () -> Complex.ofCartesian(createFixedExponentNumber(rng, -1022), createFixedExponentNumber(rng, -1022)));
}
 
Example #9
Source File: PermutationSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 */
@Test
public void testSharedStateSampler() {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final int n = 17;
    final int k = 13;
    final PermutationSampler sampler1 =
        new PermutationSampler(rng1, n, k);
    final PermutationSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(
        new RandomAssert.Sampler<int[]>() {
            @Override
            public int[] sample() {
                return sampler1.sample();
            }
        },
        new RandomAssert.Sampler<int[]>() {
            @Override
            public int[] sample() {
                return sampler2.sample();
            }
        });
}
 
Example #10
Source File: ListSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Assert the shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[])}.
 *
 * @param list Array whose entries will be shuffled (in-place).
 */
private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list) {
    final int[] array = new int[list.size()];
    ListIterator<Integer> it = list.listIterator();
    for (int i = 0; i < array.length; i++) {
        array[i] = it.next();
    }

    // Identical RNGs
    final long seed = RandomSource.createLong();
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, seed);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, seed);

    ListSampler.shuffle(rng1, list);
    PermutationSampler.shuffle(rng2, array);

    final String msg = "Type=" + list.getClass().getSimpleName();
    it = list.listIterator();
    for (int i = 0; i < array.length; i++) {
        Assert.assertEquals(msg, array[i], it.next().intValue());
    }
}
 
Example #11
Source File: SamplerBaseTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
@Test
public void testNextMethods() {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final SimpleSampler sampler = new SimpleSampler(rng2);
    final int n = 256;
    for (int i = 0; i < 3; i++) {
        Assert.assertEquals(rng1.nextDouble(), sampler.nextDouble(), 0);
        Assert.assertEquals(rng1.nextInt(), sampler.nextInt());
        Assert.assertEquals(rng1.nextInt(n), sampler.nextInt(n));
        Assert.assertEquals(rng1.nextLong(), sampler.nextLong());
    }
}
 
Example #12
Source File: SmallMeanPoissonSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad mean.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithMeanThatSetsProbabilityP0ToZero() {
    final UniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final double p0 = Double.MIN_VALUE;
    // Note: p0 = Math.exp(-mean) => mean = -Math.log(p0).
    // Add to the limit on the mean to cause p0 to be zero.
    final double mean = -Math.log(p0) + 1;
    SmallMeanPoissonSampler.of(rng, mean);
}
 
Example #13
Source File: MarsagliaTsangWangDiscreteSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the SharedStateSampler implementation using zero padded probabilities to force
 * different storage implementations.
 *
 * @param offset Offset for first given probability (i.e. the zero padding size).
 * @param prob Probability values.
 */
private static void testSharedStateSampler(int offset, int[] prob) {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    double[] probabilities = createProbabilities(offset, prob);
    final SharedStateDiscreteSampler sampler1 =
            MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng1, probabilities);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #14
Source File: ChengBetaSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 *
 * @param alpha Alpha.
 * @param beta Beta.
 */
private static void testSharedStateSampler(double alpha, double beta) {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    // Use instance constructor not factory constructor to exercise 1.X public API
    final SharedStateContinuousSampler sampler1 =
        new ChengBetaSampler(rng1, alpha, beta);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #15
Source File: DiscreteUniformSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the sample uniformity when using a small range that is a power of 2.
 */
@Test
public void testSampleUniformityWithPowerOf2Range() {
    // Test using a RNG that outputs a counter of integers.
    final UniformRandomProvider rng = new IntProvider() {
        private int bits = 0;

        @Override
        public int next() {
            // We reverse the bits because the most significant bits are used
            return Integer.reverse(bits++);
        }
    };

    // n = upper range exclusive
    final int n = 32; // power of 2
    final int[] histogram = new int[n];

    final int lower = 0;
    final int upper = n - 1;

    final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper);

    final int expected = 2;
    for (int i = expected * n; i-- > 0;) {
        histogram[sampler.sample()]++;
    }

    // This should be even across the entire range
    for (int value : histogram) {
        Assert.assertEquals(expected, value);
    }
}
 
Example #16
Source File: DiscreteUniformSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 *
 * @param lower Lower.
 * @param upper Upper.
 */
private static void testSharedStateSampler(int lower, int upper) {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    // Use instance constructor not factory constructor to exercise 1.X public API
    final SharedStateDiscreteSampler sampler1 =
        new DiscreteUniformSampler(rng1, lower, upper);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #17
Source File: ProvidersCommonParametricTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Tests uniformity of the distribution produced by {@code nextInt(int)}.
 *
 * @param rng Generator.
 * @param max Upper bound.
 * @param sampleSize Number of random values generated.
 */
private void checkNextIntegerInRange(final UniformRandomProvider rng,
                                     final int max,
                                     int sampleSize) {
    final Callable<Integer> nextMethod = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return rng.nextInt(max);
        }
    };

    checkNextInRange(max, sampleSize, nextMethod);
}
 
Example #18
Source File: SeedArrayGenerationPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @param sizes Size of the seed.
 * @return the seed
 */
@Benchmark
@Threads(4)
public long[] Threads4_createLongArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
    final UniformRandomProvider rng = sources.getGenerator();
    final long[] seed = new long[sizes.getSize()];
    for (int i = 0; i < seed.length; i++) {
        seed[i] = nextLong(FAIR_LOCK, rng);
    }
    return seed;
}
 
Example #19
Source File: RandomAssert.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Assert that following a set number of warm-up cycles the random generator produces
 * at least one non-zero output for {@link UniformRandomProvider#nextLong()} over the
 * given number of test cycles. This is used to test a poorly seeded generator can recover
 * internal state to generate "random" output.
 *
 * @param rng Random generator.
 * @param warmupCycles Number of warm-up cycles.
 * @param testCycles Number of test cycles.
 */
public static void assertNextLongNonZeroOutput(UniformRandomProvider rng,
                                               int warmupCycles, int testCycles) {
    for (int i = 0; i < warmupCycles; i++) {
        rng.nextLong();
    }
    for (int i = 0; i < testCycles; i++) {
        if (rng.nextLong() != 0L) {
            return;
        }
    }
    Assert.fail("No non-zero output after " + (warmupCycles + testCycles) + " cycles");
}
 
Example #20
Source File: ProvidersCommonParametricTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
@Test
public void testSupportedInterfaces() {
    final UniformRandomProvider rng = RandomSource.create(originalSource, null, originalArgs);
    Assert.assertEquals("isJumpable", rng instanceof JumpableUniformRandomProvider,
                        originalSource.isJumpable());
    Assert.assertEquals("isLongJumpable", rng instanceof LongJumpableUniformRandomProvider,
                        originalSource.isLongJumpable());
}
 
Example #21
Source File: SeedArrayGenerationPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @param sizes Size of the seed and compute blocks.
 * @return the seed
 */
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeedBlocks_FairLock(SeedRandomSources sources, TestSizes sizes) {
    final UniformRandomProvider rng = sources.getGenerator();
    final int[] seed = new int[sizes.getSize()];
    for (int i = 0; i < seed.length; i += sizes.getBlockSize()) {
        nextInt(FAIR_LOCK, rng, seed, i, Math.min(i + sizes.getBlockSize(), seed.length));
    }
    return seed;
}
 
Example #22
Source File: RNGUtils.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap the random generator with a new instance that will reverse the bits of
 * the native type. The input must be either a {@link RandomIntSource} or
 * {@link RandomLongSource}.
 *
 * @param rng The random generator.
 * @return the bit reversed random generator.
 * @throws ApplicationException If the input source native type is not recognised.
 * @see Integer#reverse(int)
 * @see Long#reverse(long)
 */
static UniformRandomProvider createReverseBitsProvider(final UniformRandomProvider rng) {
    if (rng instanceof RandomIntSource) {
        return new IntProvider() {
            @Override
            public int next() {
                return Integer.reverse(rng.nextInt());
            }

            @Override
            public String toString() {
                return BIT_REVERSED + rng.toString();
            }
        };
    }
    if (rng instanceof RandomLongSource) {
        return new LongProvider() {
            @Override
            public long next() {
                return Long.reverse(rng.nextLong());
            }

            @Override
            public String toString() {
                return BIT_REVERSED + rng.toString();
            }
        };
    }
    throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng);
}
 
Example #23
Source File: PoissonSamplerCachePerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @param range   The range.
 * @param bh      Data sink.
 */
@Benchmark
public void runPoissonSamplerCacheWhenEmpty(Sources sources,
                                            MeanRange range,
                                            Blackhole bh) {
    final UniformRandomProvider r = sources.getGenerator();
    final PoissonSamplerCache cache = new PoissonSamplerCache(0, 0);
    final PoissonSamplerFactory factory = new PoissonSamplerFactory() {
        @Override
        public DiscreteSampler createPoissonSampler(double mean) {
            return cache.createSharedStateSampler(r, mean);
        }
    };
    runSample(factory, range, bh);
}
 
Example #24
Source File: GaussianSampler.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param rng Generator of uniformly distributed random numbers.
 * @param source Source to copy.
 */
private GaussianSampler(UniformRandomProvider rng,
                        GaussianSampler source) {
    this.mean = source.mean;
    this.standardDeviation = source.standardDeviation;
    this.normalized = InternalUtils.newNormalizedGaussianSampler(source.normalized, rng);
}
 
Example #25
Source File: ProvidersCommonParametricTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Tests uniformity of the distribution produced by {@code nextInt(int)}.
 *
 * @param rng Generator.
 * @param max Upper bound.
 * @param sampleSize Number of random values generated.
 */
private void checkNextIntegerInRange(final UniformRandomProvider rng,
                                     final int max,
                                     int sampleSize) {
    final Callable<Integer> nextMethod = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return rng.nextInt(max);
        }
    };

    checkNextInRange(max, sampleSize, nextMethod);
}
 
Example #26
Source File: SeedArrayGenerationPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @param sizes Size of the seed.
 * @return the seed
 */
@Benchmark
@Threads(4)
public int[] Threads4_createIntArraySeed_FairLock(SeedRandomSources sources, SeedSizes sizes) {
    final UniformRandomProvider rng = sources.getGenerator();
    final int[] seed = new int[sizes.getSize()];
    for (int i = 0; i < seed.length; i++) {
        seed[i] = nextInt(FAIR_LOCK, rng);
    }
    return seed;
}
 
Example #27
Source File: DiscreteUniformSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
@Test
public void testSamplesWithRangeOf1() {
    final int upper = 99;
    final int lower = upper;
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
    final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper);
    for (int i = 0; i < 5; i++) {
        Assert.assertEquals(lower, sampler.sample());
    }
}
 
Example #28
Source File: GuideTableDiscreteSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 */
@Test
public void testSharedStateSampler() {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final double[] probabilities = {0.1, 0, 0.2, 0.3, 0.1, 0.3, 0};
    final SharedStateDiscreteSampler sampler1 =
        GuideTableDiscreteSampler.of(rng1, probabilities);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #29
Source File: PoissonSamplerCachePerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @param range   The range.
 * @param bh      Data sink.
 */
@Benchmark
public void runPoissonSampler(Sources sources,
                              MeanRange range,
                              Blackhole bh) {
    final UniformRandomProvider r = sources.getGenerator();
    final PoissonSamplerFactory factory = new PoissonSamplerFactory() {
        @Override
        public DiscreteSampler createPoissonSampler(double mean) {
            return PoissonSampler.of(r, mean);
        }
    };
    runSample(factory, range, bh);
}
 
Example #30
Source File: RejectionInversionZipfSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 */
@Test
public void testSharedStateSampler() {
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final int numberOfElements = 7;
    final double exponent = 1.23;
    final SharedStateDiscreteSampler sampler1 =
        RejectionInversionZipfSampler.of(rng1, numberOfElements, exponent);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}