org.apache.commons.rng.simple.RandomSource Java Examples

The following examples show how to use org.apache.commons.rng.simple.RandomSource. 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: UnitSphereSamplerTest.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 = 3;
    final UnitSphereSampler sampler1 =
        new UnitSphereSampler(n, rng1);
    final UnitSphereSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(
        new RandomAssert.Sampler<double[]>() {
            @Override
            public double[] sample() {
                return sampler1.nextVector();
            }
        },
        new RandomAssert.Sampler<double[]>() {
            @Override
            public double[] sample() {
                return sampler2.nextVector();
            }
        });
}
 
Example #2
Source File: ContinuousDistributionAbstractTest.java    From commons-statistics with Apache License 2.0 6 votes vote down vote up
/**
 * Test sampling
 */
@Test
void testSampler() {
    final int sampleSize = 1000;
    final ContinuousDistribution.Sampler sampler =
        distribution.createSampler(RandomSource.create(RandomSource.WELL_19937_C, 123456789L));
    final double[] sample = AbstractContinuousDistribution.sample(sampleSize, sampler);
    final double[] quartiles = TestUtils.getDistributionQuartiles(distribution);
    final double[] expected = {250, 250, 250, 250};
    final long[] counts = new long[4];

    for (int i = 0; i < sampleSize; i++) {
        TestUtils.updateCounts(sample[i], counts, quartiles);
    }
    TestUtils.assertChiSquareAccept(expected, counts, 0.001);
}
 
Example #3
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 #4
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[], int, boolean)}.
 *
 * @param list Array whose entries will be shuffled (in-place).
 * @param start Index at which shuffling begins.
 * @param towardHead Shuffling is performed for index positions between
 * {@code start} and either the end (if {@code false}) or the beginning
 * (if {@code true}) of the array.
 */
private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list,
                                                                int start,
                                                                boolean towardHead) {
    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, start, towardHead);
    PermutationSampler.shuffle(rng2, array, start, towardHead);

    final String msg = String.format("Type=%s start=%d towardHead=%b",
            list.getClass().getSimpleName(), start, towardHead);
    it = list.listIterator();
    for (int i = 0; i < array.length; i++) {
        Assert.assertEquals(msg, array[i], it.next().intValue());
    }
}
 
Example #5
Source File: Vector3DTest.java    From commons-geometry with Apache License 2.0 6 votes vote down vote up
@Test
public void testDotProduct_accuracy() {
    // we compare accurate versus naive dot product implementations
    // on regular vectors (i.e. not extreme cases like in the previous test)
    UniformRandomProvider random = RandomSource.create(RandomSource.WELL_1024_A, 553267312521321237L);
    for (int i = 0; i < 10000; ++i) {
        // arrange
        double ux = 10000 * random.nextDouble();
        double uy = 10000 * random.nextDouble();
        double uz = 10000 * random.nextDouble();
        double vx = 10000 * random.nextDouble();
        double vy = 10000 * random.nextDouble();
        double vz = 10000 * random.nextDouble();

        // act
        double sNaive = ux * vx + uy * vy + uz * vz;
        double sAccurate = Vector3D.of(ux, uy, uz).dot(Vector3D.of(vx, vy, vz));

        // assert
        Assert.assertEquals(sNaive, sAccurate, 2.5e-16 * sAccurate);
    }
}
 
Example #6
Source File: LogNormalSamplerTest.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 scale = 1.23;
    final double shape = 4.56;
    final SharedStateContinuousSampler sampler1 =
        LogNormalSampler.of(gauss, scale, shape);
    sampler1.withUniformRandomProvider(rng2);
}
 
Example #7
Source File: BetaDistributionTest.java    From commons-statistics with Apache License 2.0 6 votes vote down vote up
@Test
void testMomentsSampling() {
    final UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_1024_A,
                                                          123456789L);
    final int numSamples = 1000;
    for (final double alpha : ALPHA_BETAS) {
        for (final double beta : ALPHA_BETAS) {
            final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);
            final double[] observed = AbstractContinuousDistribution.sample(numSamples,
                    betaDistribution.createSampler(rng));
            Arrays.sort(observed);

            Assertions.assertEquals(betaDistribution.getMean(), StatUtils.mean(observed),
                                    EPSILON, () -> String.format("E[Beta(%.2f, %.2f)]", alpha, beta));
            Assertions.assertEquals(betaDistribution.getVariance(), StatUtils.variance(observed),
                                    EPSILON, () -> String.format("Var[Beta(%.2f, %.2f)]", alpha, beta));
        }
    }
}
 
Example #8
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 #9
Source File: CombinationSamplerTest.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 = 3;
    final CombinationSampler sampler1 =
        new CombinationSampler(rng1, n, k);
    final CombinationSampler 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: PoissonSamplerCacheTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Check poisson samples are the same from the {@link PoissonSampler}
 * and {@link PoissonSamplerCache}.
 *
 * @param minMean the min mean of the cache
 * @param maxMean the max mean of the cache
 */
private void checkComputeSameSamplesAsPoissonSampler(int minMean,
                                                     int maxMean) {
    // Two identical RNGs
    final RandomSource source = RandomSource.SPLIT_MIX_64;
    final long seed = RandomSource.createLong();
    final RestorableUniformRandomProvider rng1 =
            RandomSource.create(source, seed);
    final RestorableUniformRandomProvider rng2 =
            RandomSource.create(source, seed);

    // Create the cache with the given range
    final PoissonSamplerCache cache =
            createPoissonSamplerCache(minMean, maxMean);
    // Test all means in the test range (which may be different
    // from the cache range).
    for (int i = minRange; i <= maxRange; i++) {
        // Test integer mean (no SmallMeanPoissonSampler required)
        testPoissonSamples(rng1, rng2, cache, i);
        // Test non-integer mean (SmallMeanPoissonSampler required)
        testPoissonSamples(rng1, rng2, cache, i + 0.5);
    }
}
 
Example #11
Source File: CollectionSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleTrivial() {
    final ArrayList<String> list = new ArrayList<String>();
    list.add("Apache");
    list.add("Commons");
    list.add("RNG");

    final CollectionSampler<String> sampler =
        new CollectionSampler<String>(RandomSource.create(RandomSource.MWC_256),
                                      list);
    final String word = sampler.sample();
    for (String w : list) {
        if (word.equals(w)) {
            return;
        }
    }
    Assert.fail(word + " not in list");
}
 
Example #12
Source File: DiskGeneratorTest.java    From commons-geometry with Apache License 2.0 6 votes vote down vote up
@Test
public void testRandom() {
    // arrange
    final UniformRandomProvider random = RandomSource.create(RandomSource.WELL_1024_A,
                                                             0x12faa818373ffe90L);
    final UnitSphereSampler sr = new UnitSphereSampler(2, random);
    for (int i = 0; i < 500; ++i) {
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector2D refCenter = Vector2D.linearCombination(d, Vector2D.of(sr.nextVector()));
        List<Vector2D> support = new ArrayList<>();
        for (int j = 0; j < 3; ++j) {
            support.add(Vector2D.linearCombination(1.0, refCenter, refRadius, Vector2D.of(sr.nextVector())));
        }

        // act
        EnclosingBall<Vector2D> disk = generator.ballOnSupport(support);

        // assert
        Assert.assertEquals(0.0, refCenter.distance(disk.getCenter()), 3e-9 * refRadius);
        Assert.assertEquals(refRadius, disk.getRadius(), 7e-10 * refRadius);
    }
}
 
Example #13
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 #14
Source File: InverseTransformContinuousSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 */
@Test
public void testSharedStateSampler() {
    ContinuousInverseCumulativeProbabilityFunction function =
        new ContinuousInverseCumulativeProbabilityFunction() {
            @Override
            public double inverseCumulativeProbability(double p) {
                return 456.99 * p;
            }
    };
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final SharedStateContinuousSampler sampler1 =
        InverseTransformContinuousSampler.of(rng1, function);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #15
Source File: ComplexTest.java    From commons-numbers with Apache License 2.0 5 votes vote down vote up
@Test
void testPolarConstructorAbsArg() {
    // The test should work with any seed but use a fixed seed to avoid build
    // instability.
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, 678678638L);
    for (int i = 0; i < 10; i++) {
        final double rho = rng.nextDouble();
        // Range (pi, pi]: lower exclusive, upper inclusive
        final double theta = pi - rng.nextDouble() * 2 * pi;
        final Complex z = Complex.ofPolar(rho, theta);
        // Match within 1 ULP
        Assertions.assertEquals(rho, z.abs(), Math.ulp(rho));
        Assertions.assertEquals(theta, z.arg(), Math.ulp(theta));
    }
}
 
Example #16
Source File: LinearCombinationsTest.java    From commons-numbers with Apache License 2.0 5 votes vote down vote up
/**
 * Test the sum of vectors composed of sub-vectors of [a1, a2, a3, a4] * [a1, a2, -a3, -a4]
 * where a1^2 + a2^2 = 1 and a3^2 + a4^2 = 1 such that the sum is approximately 0 every
 * 4 products. This is a test that is failed by various implementations that accumulate the
 * round-off sum in single or 2-fold precision.
 */
@Test
void testSumZero() {
    // Fixed seed for stability
    final UniformRandomProvider rng = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP, 876543L);
    final int size = 10;
    // Create random doublets of pairs of numbers that sum to 1 or -1.
    for (int length = 4; length <= 12; length += 4) {
        final double[] a = new double[length];
        final double[] b = new double[length];
        for (int i = 0; i < size; i++) {
            // Flip-flop above and below zero
            double sign = 1;
            for (int k = 0; k < length; k += 4) {
                // Create 2 complex cis numbers
                final double theta1 = rng.nextDouble() * Math.PI / 2;
                final double theta2 = rng.nextDouble() * Math.PI / 2;
                a[k + 0] = b[k + 0] = Math.cos(theta1);
                a[k + 1] = b[k + 1] = Math.sin(theta1);
                a[k + 2] = b[k + 2] = Math.cos(theta2);
                a[k + 3] = b[k + 3] = Math.sin(theta2);
                a[k + 0] *= sign;
                a[k + 1] *= sign;
                a[k + 2] *= sign;
                a[k + 3] *= sign;
                // Invert second pair.
                // The sum of the pairs should be zero +/- floating point error.
                a[k + 2] = -a[k + 2];
                a[k + 3] = -a[k + 3];
                sign = -sign;
            }
            assertValue(LinearCombinations.DotK.DOT_3.value(a, b), a, b);
        }
    }
}
 
Example #17
Source File: DiceGameApplication.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Application's entry point.
 *
 * @param args Arguments, in the following order
 * <ol>
 *  <li>Number of games</li>
 *  <li>Number of players</li>
 *  <li>Number of rounds per game</li>
 *  <li>RNG {@link RandomSource identifier}</li>
 * </ol>
 */
public static void main(String[] args) {
    final int numGames = Integer.parseInt(args[0]);
    final DiceGameApplication app = new DiceGameApplication(Integer.parseInt(args[1]),
                                                            Integer.parseInt(args[2]),
                                                            RandomSource.valueOf(args[3]));

    app.displayModuleInfo();

    for (int i = 1; i <= numGames; i++) {
        System.out.println("--- Game " + i + " ---");
        System.out.println(display(app.game.play()));
    }
}
 
Example #18
Source File: DiceGameApplication.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Application.
 *
 * @param numPlayers Number of players.
 * @param numRounds Number of rounds per game.
 * @param identifier RNG algorithm identifier.
 */
private DiceGameApplication(int numPlayers,
                            int numRounds,
                            RandomSource identifier) {
    game = new DiceGame(numPlayers, numRounds,
                        RandomSource.create(identifier),
                        4.3, 2.1);
}
 
Example #19
Source File: RandomStringGeneratorTest.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
@Test
public void generateTextWithThreadSafe() {

    UniformRandomProvider rng = RandomSource.create(RandomSource.MT);
    RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .withinRange('a', 'z')
            .usingRandom(rng::nextInt) // uses Java 8 syntax
            .build();
    for (int i = 0; i < 10; i++) {
        System.out.println(generator.generate(10));
    }

}
 
Example #20
Source File: InverseTransformParetoSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad shape.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithZeroShape() {
    final RestorableUniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final double scale = 1;
    final double shape = 0;
    InverseTransformParetoSampler.of(rng, scale, shape);
}
 
Example #21
Source File: KempSmallMeanPoissonSamplerTest.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 mean = 1.23;
    final SharedStateDiscreteSampler sampler1 =
        KempSmallMeanPoissonSampler.of(rng1, mean);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #22
Source File: PoissonSamplerCacheTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test createSharedStateSampler() with a mean that is too large.
 */
@Test(expected = IllegalArgumentException.class)
public void testCreateSharedStateSamplerThrowsWithNonIntegerMean() {
    final RestorableUniformRandomProvider rng =
            RandomSource.create(RandomSource.SPLIT_MIX_64);
    final PoissonSamplerCache cache = createPoissonSamplerCache();
    final double mean = Integer.MAX_VALUE + 1.0;
    cache.createSharedStateSampler(rng, mean);
}
 
Example #23
Source File: ChengBetaSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the toString method. This is added to ensure coverage as the factory constructor
 * used in other tests does not create an instance of the wrapper class.
 */
@Test
public void testToString() {
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    Assert.assertTrue(new ChengBetaSampler(rng, 1.0, 2.0).toString()
            .toLowerCase().contains("beta"));
}
 
Example #24
Source File: MarsagliaNormalisedGaussianSamplerTest.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 SharedStateContinuousSampler sampler1 =
        MarsagliaNormalizedGaussianSampler.<MarsagliaNormalizedGaussianSampler>of(rng1);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #25
Source File: ResultsCommand.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Write the results as a text table.
 *
 * @param out Output stream.
 * @param results Results.
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void writeTXT(OutputStream out,
                             List<TestResult> results) throws IOException {
    // Identify all:
    // RandomSources, bit-reversed, test names,
    final List<RandomSource> randomSources = getRandomSources(results);
    final List<Boolean> bitReversed = getBitReversed(results);
    final List<String> testNames = getTestNames(results);

    // Create columns for RandomSource, bit-reversed, each test name.
    // Make bit-reversed column optional if no generators are bit reversed.
    final boolean showBitReversedColumn = bitReversed.contains(Boolean.TRUE);

    final List<List<String>> columns = createTXTColumns(testNames, showBitReversedColumn);

    // Add all data
    // This will collate results for each combination of 'RandomSource + bitReversed'
    for (final RandomSource randomSource : randomSources) {
        for (final boolean reversed : bitReversed) {
            int i = 0;
            columns.get(i++).add(randomSource.toString());
            if (showBitReversedColumn) {
                columns.get(i++).add(Boolean.toString(reversed));
            }
            for (final String testName : testNames) {
                final List<TestResult> testResults = getTestResults(results, randomSource,
                        reversed, testName);
                columns.get(i++).add(testResults.stream()
                                                .map(TestResult::getFailureSummaryString)
                                                .collect(Collectors.joining(",")));
                columns.get(i++).add(getFailuresSummary(testResults));
            }
        }
    }

    writeColumns(out, columns);
}
 
Example #26
Source File: RngDataOutputTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntBigEndian() throws IOException {
    assertRngOutput(RandomSource.PCG_MCG_XSH_RS_32,
        UnaryOperator.identity(),
        RngDataOutputTest::writeInt,
        RngDataOutput::ofInt, ByteOrder.BIG_ENDIAN);
}
 
Example #27
Source File: LogNormalSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad shape.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithNegativeScale() {
    final RestorableUniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final NormalizedGaussianSampler gauss = new ZigguratNormalizedGaussianSampler(rng);
    final double scale = -1e-6;
    final double shape = 1;
    LogNormalSampler.of(gauss, scale, shape);
}
 
Example #28
Source File: StressTestData.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param randomSource The random source.
 * @param args The arguments used to construct the random source (can be {@code null}).
 */
StressTestData(RandomSource randomSource,
               Object[] args) {
    // The default ID is defined by the enum order.
    this(Integer.toString(randomSource.ordinal() + 1),
         randomSource,
         args,
         // Ignore by default (trials = 0) any source that has arguments
         args == null ? 1 : 0);
}
 
Example #29
Source File: AhrensDieterExponentialSamplerTest.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 mean = 1.23;
    final SharedStateContinuousSampler sampler1 =
        AhrensDieterExponentialSampler.of(rng1, mean);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example #30
Source File: PoissonSamplerCachePerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/** Instantiates generator. */
@Setup
public void setup() {
    final RandomSource randomSource = RandomSource
            .valueOf(randomSourceName);
    // Use the same seed
    generator = RandomSource.create(randomSource, SEED.clone());
    state = generator.saveState();
}