Java Code Examples for org.apache.commons.rng.simple.RandomSource#create()

The following examples show how to use org.apache.commons.rng.simple.RandomSource#create() . 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: 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 2
Source File: LargeMeanPoissonSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Test the {@link LargeMeanPoissonSampler} returns the same samples when it
 * is created using the saved state.
 */
@Test
public void testCanComputeSameSamplesWhenConstructedWithState() {
    // Two identical RNGs
    final RestorableUniformRandomProvider rng1 =
            RandomSource.create(RandomSource.MWC_256);
    final RandomProviderState state = rng1.saveState();
    final RestorableUniformRandomProvider rng2 =
            RandomSource.create(RandomSource.MWC_256);
    rng2.restoreState(state);

    // The sampler is suitable for mean > 40
    for (int i = 40; i < 44; i++) {
        // Test integer mean (no SmallMeanPoissonSampler required)
        testPoissonSamples(rng1, rng2, i);
        // Test non-integer mean (SmallMeanPoissonSampler required)
        testPoissonSamples(rng1, rng2, i + 0.5);
    }
}
 
Example 3
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 4
Source File: InverseTransformDiscreteSamplerTest.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Test the SharedStateSampler implementation.
 */
@Test
public void testSharedStateSampler() {
    DiscreteInverseCumulativeProbabilityFunction function =
        new DiscreteInverseCumulativeProbabilityFunction() {
            @Override
            public int inverseCumulativeProbability(double p) {
                return (int) Math.round(789 * p);
            }
    };
    final UniformRandomProvider rng1 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final UniformRandomProvider rng2 = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    final SharedStateDiscreteSampler sampler1 =
        InverseTransformDiscreteSampler.of(rng1, function);
    final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example 5
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 6
Source File: MarsagliaTsangWangDiscreteSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test samples from a distribution expressed using {@code double} probabilities.
 */
@Test
public void testRealProbabilityDistributionSamples() {
    // These do not have to sum to 1
    final double[] probabilities = new double[11];
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
    for (int i = 0; i < probabilities.length; i++) {
        probabilities[i] = rng.nextDouble();
    }

    // First test the table is completely filled to 2^30
    final UniformRandomProvider dummyRng = new FixedSequenceIntProvider(new int[] {0xffffffff});
    final SharedStateDiscreteSampler dummySampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(dummyRng, probabilities);
    // This will throw if the table is incomplete as it hits the upper limit
    dummySampler.sample();

    // Do a test of the actual sampler
    final SharedStateDiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, probabilities);

    final int numberOfSamples = 10000;
    final long[] samples = new long[probabilities.length];
    for (int i = 0; i < numberOfSamples; i++) {
        samples[sampler.sample()]++;
    }

    final ChiSquareTest chiSquareTest = new ChiSquareTest();
    // Pass if we cannot reject null hypothesis that the distributions are the same.
    Assert.assertFalse(chiSquareTest.chiSquareTest(probabilities, samples, 0.001));
}
 
Example 7
Source File: DiscreteUniformSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad range.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithLowerAboveUpper() {
    final int upper = 55;
    final int lower = upper + 1;
    final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, 0L);
    DiscreteUniformSampler.of(rng, lower, upper);
}
 
Example 8
Source File: ContinuousUniformSamplerTest.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 low = 1.23;
    final double high = 4.56;
    final SharedStateContinuousSampler sampler1 =
        ContinuousUniformSampler.of(rng1, low, high);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example 9
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 10
Source File: GeometricSamplersPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/** Instantiates sampler. */
@Setup
public void setup() {
    final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
    final UniformRandomProvider rng = RandomSource.create(randomSource);
    if ("GeometricSampler".equals(samplerType)) {
        sampler = GeometricSampler.of(rng, probabilityOfSuccess);
    } else {
        final DiscreteInverseCumulativeProbabilityFunction geometricFunction =
            new GeometricDiscreteInverseCumulativeProbabilityFunction(probabilityOfSuccess);
        sampler = InverseTransformDiscreteSampler.of(rng, geometricFunction);
    }
}
 
Example 11
Source File: AhrensDieterExponentialSamplerTest.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 testConstructorThrowsWithZeroMean() {
    final RestorableUniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final double mean = 0;
    AhrensDieterExponentialSampler.of(rng, mean);
}
 
Example 12
Source File: InverseTransformParetoSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad scale.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithZeroScale() {
    final RestorableUniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final double scale = 0;
    final double shape = 1;
    InverseTransformParetoSampler.of(rng, scale, shape);
}
 
Example 13
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 14
Source File: InverseTransformParetoSamplerTest.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 scale = 1.23;
    final double shape = 4.56;
    final SharedStateContinuousSampler sampler1 =
        InverseTransformParetoSampler.of(rng1, scale, shape);
    final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2);
    RandomAssert.assertProduceSameSequence(sampler1, sampler2);
}
 
Example 15
Source File: ThreadLocalPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * @param sources Source of randomness.
 * @return the result
 */
@Benchmark
@Threads(4)
public long randomSourceCreate(Sources sources) {
    final UniformRandomProvider rng = RandomSource.create(sources.getRandomSource());
    long result = 0;
    for (int i = 0; i < numValues; i++) {
        result = result ^ rng.nextLong();
    }
    return result;
}
 
Example 16
Source File: BoxMullerGaussianSamplerTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Test the constructor with a bad standard deviation.
 */
@Test(expected = IllegalArgumentException.class)
public void testConstructorThrowsWithZeroStandardDeviation() {
    final RestorableUniformRandomProvider rng =
        RandomSource.create(RandomSource.SPLIT_MIX_64);
    final double mean = 1;
    final double standardDeviation = 0;
    @SuppressWarnings("unused")
    final BoxMullerGaussianSampler sampler =
        new BoxMullerGaussianSampler(rng, mean, standardDeviation);
}
 
Example 17
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 18
Source File: PoissonSamplerCacheTest.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Check poisson samples are the same from the {@link PoissonSampler}
 * and a {@link PoissonSamplerCache} created reusing values.
 *
 * <p>Note: This cannot check the cache values were reused but ensures
 * that a new cache created with a range functions correctly.
 *
 * @param minMean  the min mean of the cache
 * @param maxMean  the max mean of the cache
 * @param minMean2 the min mean of the second cache
 * @param maxMean2 the max mean of the second cache
 */
private void checkComputeSameSamplesAsPoissonSamplerReusingCache(int minMean,
                                                                 int maxMean,
                                                                 int minMean2,
                                                                 int maxMean2) {
    // 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 and fill it
    final PoissonSamplerCache cache =
            createPoissonSamplerCache(minMean, maxMean);
    // Test all means in the test range (which may be different
    // from the cache range).
    for (int i = minMean; i <= maxMean; i++) {
        cache.createSharedStateSampler(rng1, i);
    }

    final PoissonSamplerCache cache2 = cache.withRange(minMean2, maxMean2);
    Assert.assertNotSame("WithRange cache is the same object", cache, cache2);

    // 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, cache2, i);
        // Test non-integer mean (SmallMeanPoissonSampler required)
        testPoissonSamples(rng1, rng2, cache2, i + 0.5);
    }
}
 
Example 19
Source File: CollectionSamplerTest.java    From commons-rng with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testSamplePrecondition() {
    // Must fail for empty collection.
    new CollectionSampler<String>(RandomSource.create(RandomSource.MT),
                                  new ArrayList<String>());
}
 
Example 20
Source File: RandomStringConfig.java    From spring-boot-cookbook with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * Generates random Unicode strings containing the specified number of code points.
 * Instances are created using a builder class, which allows the
 * callers to define the properties of the generator. See the documentation for the
 * {@link RandomStringGenerator.Builder} class to see available properties.
 * </p>
 * <pre>
 * // Generates a 20 code point string, using only the letters a-z
 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
 *     .withinRange('a', 'z').build();
 * String randomLetters = generator.generate(20);
 * </pre>
 * <pre>
 * // Using Apache Commons RNG for randomness
 * UniformRandomProvider rng = RandomSource.create(...);
 * // Generates a 20 code point string, using only the letters a-z
 * RandomStringGenerator generator = new RandomStringGenerator.Builder()
 *     .withinRange('a', 'z')
 *     .usingRandom(rng::nextInt) // uses Java 8 syntax
 *     .build();
 * String randomLetters = generator.generate(20);
 * </pre>
 * <p>
 * {@code RandomStringBuilder} instances are thread-safe when using the
 * default random number generator (RNG). If a custom RNG is set by calling the method
 * {@link RandomStringGenerator.Builder#usingRandom(TextRandomProvider) Builder.usingRandom(TextRandomProvider)}, thread-safety
 * must be ensured externally.
 * </p>
 *
 * @since 1.1
 */
@Bean
public RandomStringGenerator randomStringGenerator() {
    UniformRandomProvider rng = RandomSource.create(RandomSource.MT);
    return new RandomStringGenerator.Builder()
            .withinRange('a', 'z')
            .usingRandom(rng::nextInt) // uses Java 8 syntax
            .build();
}