Java Code Examples for org.apache.commons.math3.random.RandomGenerator#nextDouble()

The following examples show how to use org.apache.commons.math3.random.RandomGenerator#nextDouble() . 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: LogitTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testValueWithInverseFunction() {
    final double lo = 2;
    final double hi = 3;
    final Logit f = new Logit(lo, hi);
    final Sigmoid g = new Sigmoid(lo, hi);
    RandomGenerator random = new Well1024a(0x49914cdd9f0b8db5l);
    final UnivariateDifferentiableFunction id = FunctionUtils.compose((UnivariateDifferentiableFunction) g,
                                                            (UnivariateDifferentiableFunction) f);

    for (int i = 0; i < 10; i++) {
        final double x = lo + random.nextDouble() * (hi - lo);
        Assert.assertEquals(x, id.value(new DerivativeStructure(1, 1, 0, x)).getValue(), EPS);
    }

    Assert.assertEquals(lo, id.value(new DerivativeStructure(1, 1, 0, lo)).getValue(), EPS);
    Assert.assertEquals(hi, id.value(new DerivativeStructure(1, 1, 0, hi)).getValue(), EPS);
}
 
Example 2
Source File: LogitTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testValueWithInverseFunction() {
    final double lo = 2;
    final double hi = 3;
    final Logit f = new Logit(lo, hi);
    final Sigmoid g = new Sigmoid(lo, hi);
    RandomGenerator random = new Well1024a(0x49914cdd9f0b8db5l);
    final UnivariateDifferentiableFunction id = FunctionUtils.compose((UnivariateDifferentiableFunction) g,
                                                            (UnivariateDifferentiableFunction) f);

    for (int i = 0; i < 10; i++) {
        final double x = lo + random.nextDouble() * (hi - lo);
        Assert.assertEquals(x, id.value(new DerivativeStructure(1, 1, 0, x)).getValue(), EPS);
    }

    Assert.assertEquals(lo, id.value(new DerivativeStructure(1, 1, 0, lo)).getValue(), EPS);
    Assert.assertEquals(hi, id.value(new DerivativeStructure(1, 1, 0, hi)).getValue(), EPS);
}
 
Example 3
Source File: FastByIDMapTest.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersusHashMap() {
  FastByIDMap<String> actual = new FastByIDMap<String>();
  Map<Long, String> expected = Maps.newHashMapWithExpectedSize(1000000);
  RandomGenerator r = RandomManager.getRandom();
  for (int i = 0; i < 1000000; i++) {
    double d = r.nextDouble();
    Long key = (long) r.nextInt(100);
    if (d < 0.4) {
      assertEquals(expected.get(key), actual.get(key));
    } else {
      if (d < 0.7) {
        assertEquals(expected.put(key, "bang"), actual.put(key, "bang"));
      } else {
        assertEquals(expected.remove(key), actual.remove(key));
      }
      assertEquals(expected.size(), actual.size());
      assertEquals(expected.isEmpty(), actual.isEmpty());
    }
  }
}
 
Example 4
Source File: WelzlEncloser3DTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLargeSamples() throws IOException {
    RandomGenerator random = new Well1024a(0x35ddecfc78131e1dl);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(3, random);
    for (int k = 0; k < 50; ++k) {

        // define the reference sphere we want to compute
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector3D refCenter = new Vector3D(d, new Vector3D(sr.nextVector()));
        // set up a large sample inside the reference sphere
        int nbPoints = random.nextInt(1000);
        List<Vector3D> points = new ArrayList<Vector3D>();
        for (int i = 0; i < nbPoints; ++i) {
            double r = refRadius * random.nextDouble();
            points.add(new Vector3D(1.0, refCenter, r, new Vector3D(sr.nextVector())));
        }

        // test we find a sphere at most as large as the one used for random drawings
        checkSphere(points, refRadius);

    }
}
 
Example 5
Source File: WelzlEncloser3DTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLargeSamples() throws IOException {
    RandomGenerator random = new Well1024a(0x35ddecfc78131e1dl);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(3, random);
    for (int k = 0; k < 50; ++k) {

        // define the reference sphere we want to compute
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector3D refCenter = new Vector3D(d, new Vector3D(sr.nextVector()));
        // set up a large sample inside the reference sphere
        int nbPoints = random.nextInt(1000);
        List<Vector3D> points = new ArrayList<Vector3D>();
        for (int i = 0; i < nbPoints; ++i) {
            double r = refRadius * random.nextDouble();
            points.add(new Vector3D(1.0, refCenter, r, new Vector3D(sr.nextVector())));
        }

        // test we find a sphere at most as large as the one used for random drawings
        checkSphere(points, refRadius);

    }
}
 
Example 6
Source File: DiskGeneratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandom() {
    final RandomGenerator random = new Well1024a(0x12faa818373ffe90l);
    final UnitSphereRandomVectorGenerator sr = new UnitSphereRandomVectorGenerator(2, random);
    for (int i = 0; i < 500; ++i) {
        double d = 25 * random.nextDouble();
        double refRadius = 10 * random.nextDouble();
        Vector2D refCenter = new Vector2D(d, new Vector2D(sr.nextVector()));
        List<Vector2D> support = new ArrayList<Vector2D>();
        for (int j = 0; j < 3; ++j) {
            support.add(new Vector2D(1.0, refCenter, refRadius, new Vector2D(sr.nextVector())));
        }
        EnclosingBall<Euclidean2D, Vector2D> disk = new DiskGenerator().ballOnSupport(support);
        Assert.assertEquals(0.0, refCenter.distance(disk.getCenter()), 3e-9 * refRadius);
        Assert.assertEquals(refRadius, disk.getRadius(), 7e-10 * refRadius);
    }
    
}
 
Example 7
Source File: SelfOrganizingMaps.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
private static void assignVectorsParallel(FastByIDMap<float[]> vectors, double samplingRate, Node[][] map) {
  boolean doSample = samplingRate < 1.0;
  RandomGenerator random = RandomManager.getRandom();
  for (FastByIDMap.MapEntry<float[]> entry : vectors.entrySet()) {
    if (doSample && random.nextDouble() > samplingRate) {
      continue;
    }
    float[] V = entry.getValue();
    int[] bmuCoordinates = findBestMatchingUnit(V, map);
    if (bmuCoordinates != null) {
      Node node = map[bmuCoordinates[0]][bmuCoordinates[1]];
      float[] center = node.getCenter();
      double currentScore =
          SimpleVectorMath.dot(V, center) / (SimpleVectorMath.norm(center) * SimpleVectorMath.norm(V));
      Pair<Double,Long> newAssignedID = new Pair<Double,Long>(currentScore, entry.getKey());
      node.addAssignedID(newAssignedID);
    }
  }
}
 
Example 8
Source File: FastIDSetTest.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersusHashSet() {
  FastIDSet actual = new FastIDSet(1);
  Collection<Integer> expected = new HashSet<Integer>(1000000);
  RandomGenerator r = RandomManager.getRandom();
  for (int i = 0; i < 1000000; i++) {
    double d = r.nextDouble();
    Integer key = r.nextInt(100);
    if (d < 0.4) {
      assertEquals(expected.contains(key), actual.contains(key));
    } else {
      if (d < 0.7) {
        assertEquals(expected.add(key), actual.add(key));
      } else {
        assertEquals(expected.remove(key), actual.remove(key));
      }
      assertEquals(expected.size(), actual.size());
      assertEquals(expected.isEmpty(), actual.isEmpty());
    }
  }
}
 
Example 9
Source File: UniformCrossover.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
private ChromosomePair mate(final AbstractListChromosome<T> first,
                            final AbstractListChromosome<T> second) throws DimensionMismatchException {
    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1Rep = new ArrayList<T>(first.getLength());
    final List<T> child2Rep = new ArrayList<T>(second.getLength());

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();

    for (int index = 0; index < length; index++) {

        if (random.nextDouble() < ratio) {
            // swap the bits -> take other parent
            child1Rep.add(parent2Rep.get(index));
            child2Rep.add(parent1Rep.get(index));
        } else {
            child1Rep.add(parent1Rep.get(index));
            child2Rep.add(parent2Rep.get(index));
        }
    }

    return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
                              second.newFixedLengthChromosome(child2Rep));
}
 
Example 10
Source File: UniformCrossover.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper for {@link #crossover(Chromosome, Chromosome)}. Performs the actual crossover.
 *
 * @param first the first chromosome
 * @param second the second chromosome
 * @return the pair of new chromosomes that resulted from the crossover
 * @throws DimensionMismatchException if the length of the two chromosomes is different
 */
private ChromosomePair mate(final AbstractListChromosome<T> first,
                            final AbstractListChromosome<T> second) throws DimensionMismatchException {
    final int length = first.getLength();
    if (length != second.getLength()) {
        throw new DimensionMismatchException(second.getLength(), length);
    }

    // array representations of the parents
    final List<T> parent1Rep = first.getRepresentation();
    final List<T> parent2Rep = second.getRepresentation();
    // and of the children
    final List<T> child1Rep = new ArrayList<T>(first.getLength());
    final List<T> child2Rep = new ArrayList<T>(second.getLength());

    final RandomGenerator random = GeneticAlgorithm.getRandomGenerator();

    for (int index = 0; index < length; index++) {

        if (random.nextDouble() < ratio) {
            // swap the bits -> take other parent
            child1Rep.add(parent2Rep.get(index));
            child2Rep.add(parent1Rep.get(index));
        } else {
            child1Rep.add(parent1Rep.get(index));
            child2Rep.add(parent2Rep.get(index));
        }
    }

    return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
                              second.newFixedLengthChromosome(child2Rep));
}
 
Example 11
Source File: ExtendedFieldElementAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private double[] generateDouble (final RandomGenerator r, int n) {
    double[] a = new double[n];
    for (int i = 0; i < n; ++i) {
        a[i] = r.nextDouble();
    }
    return a;
}
 
Example 12
Source File: CircleTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testTransform() {
    RandomGenerator random = new Well1024a(0x16992fc4294bf2f1l);
    UnitSphereRandomVectorGenerator sphRandom = new UnitSphereRandomVectorGenerator(3, random);
    for (int i = 0; i < 100; ++i) {

        Rotation r = new Rotation(new Vector3D(sphRandom.nextVector()),
                                  FastMath.PI * random.nextDouble());
        Transform<Sphere2D, Sphere1D> t = Circle.getTransform(r);

        S2Point  p = new S2Point(new Vector3D(sphRandom.nextVector()));
        S2Point tp = (S2Point) t.apply(p);
        Assert.assertEquals(0.0, r.applyTo(p.getVector()).distance(tp.getVector()), 1.0e-10);

        Circle  c = new Circle(new Vector3D(sphRandom.nextVector()), 1.0e-10);
        Circle tc = (Circle) t.apply(c);
        Assert.assertEquals(0.0, r.applyTo(c.getPole()).distance(tc.getPole()),   1.0e-10);
        Assert.assertEquals(0.0, r.applyTo(c.getXAxis()).distance(tc.getXAxis()), 1.0e-10);
        Assert.assertEquals(0.0, r.applyTo(c.getYAxis()).distance(tc.getYAxis()), 1.0e-10);
        Assert.assertEquals(c.getTolerance(), ((Circle) t.apply(c)).getTolerance(), 1.0e-10);

        SubLimitAngle  sub = new LimitAngle(new S1Point(MathUtils.TWO_PI * random.nextDouble()),
                                            random.nextBoolean(), 1.0e-10).wholeHyperplane();
        Vector3D psub = c.getPointAt(((LimitAngle) sub.getHyperplane()).getLocation().getAlpha());
        SubLimitAngle tsub = (SubLimitAngle) t.apply(sub, c, tc);
        Vector3D ptsub = tc.getPointAt(((LimitAngle) tsub.getHyperplane()).getLocation().getAlpha());
        Assert.assertEquals(0.0, r.applyTo(psub).distance(ptsub), 1.0e-10);

    }
}
 
Example 13
Source File: ExtendedFieldElementAbstractTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private double[] generateDouble (final RandomGenerator r, int n) {
    double[] a = new double[n];
    for (int i = 0; i < n; ++i) {
        a[i] = r.nextDouble();
    }
    return a;
}
 
Example 14
Source File: MockRDFClassificationInputGenerator.java    From oryx with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String, String> generate(int id, RandomGenerator random) {
  boolean positive = id % 2 != 0;
  String target = positive ? "banana" : "apple";
  // 10% chance of wrong predictor
  String predictor = (positive ^ (random.nextDouble() < 0.1)) ? "yellow" : "red";
  return new Pair<>(null, predictor + ',' + target);
}
 
Example 15
Source File: MathUtils.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a binomial distributed number using
 * the given rng
 *
 * @param rng
 * @param n
 * @param p
 * @return
 */
public static int binomial(RandomGenerator rng, int n, double p) {
    if ((p < 0) || (p > 1)) {
        return 0;
    }
    int c = 0;
    for (int i = 0; i < n; i++) {
        if (rng.nextDouble() < p) {
            c++;
        }
    }
    return c;
}
 
Example 16
Source File: RandomCategoricalRDFDataGenerator.java    From oryx with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String,String> generate(int id, RandomGenerator random) {
  List<String> elements = new ArrayList<>(n + 2);
  elements.add(Integer.toString(id));
  boolean positive = true;
  for (int i = 0; i < n; i++) {
    double d = random.nextDouble();
    if (d < 0.5) {
      positive = false;
    }
    elements.add(Double.toString(d));
  }
  elements.add(Boolean.toString(positive));
  return new Pair<>(Integer.toString(id), TextUtils.joinDelimited(elements, ','));
}
 
Example 17
Source File: Endpoints.java    From oryx with Apache License 2.0 5 votes vote down vote up
Endpoint chooseEndpoint(RandomGenerator random) {
  double p = random.nextDouble();
  int i = 0;
  while (i < cumulativeProbs.length && p >= cumulativeProbs[i]) {
    i++;
  }
  return endpoints[i];
}
 
Example 18
Source File: RandomManagerRandomTest.java    From oryx with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testRandomState() {
  RandomGenerator generator = RandomManager.getRandom();
  double unseededValue = generator.nextDouble();
  RandomManager.useTestSeed();
  double seededValue = generator.nextDouble();
  assertNotEquals(unseededValue, seededValue);
  assertEquals(seededValue, RandomManager.getRandom().nextDouble());
}
 
Example 19
Source File: ClusterAlgorithmComparison.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static List<Vector2D> makeBlobs(int samples, int centers, double clusterStd,
                                       double min, double max, boolean shuffle, RandomGenerator random) {

    NormalDistribution dist = new NormalDistribution(random, 0.0, clusterStd, 1e-9);

    double range = max - min;
    Vector2D[] centerPoints = new Vector2D[centers];
    for (int i = 0; i < centers; i++) {
        double x = random.nextDouble() * range + min;
        double y = random.nextDouble() * range + min;
        centerPoints[i] = new Vector2D(x, y);
    }
    
    int[] nSamplesPerCenter = new int[centers];
    int count = samples / centers;
    Arrays.fill(nSamplesPerCenter, count);
    
    for (int i = 0; i < samples % centers; i++) {
        nSamplesPerCenter[i]++;
    }
    
    List<Vector2D> points = new ArrayList<Vector2D>();
    for (int i = 0; i < centers; i++) {
        for (int j = 0; j < nSamplesPerCenter[i]; j++) {
            Vector2D point = new Vector2D(dist.sample(), dist.sample());
            points.add(point.add(centerPoints[i]));
        }
    }
    
    if (shuffle) {
        Collections.shuffle(points, new RandomAdaptor(random));
    }

    return points;
}
 
Example 20
Source File: MathUtils.java    From deeplearning4j with Apache License 2.0 2 votes vote down vote up
/**
 * Generates a random integer between the specified numbers
 *
 * @param begin the begin of the interval
 * @param end   the end of the interval
 * @return an int between begin and end
 */
public static int randomNumberBetween(double begin, double end, RandomGenerator rng) {
    if (begin > end)
        throw new IllegalArgumentException("Begin must not be less than end");
    return (int) begin + (int) (rng.nextDouble() * ((end - begin) + 1));
}