Example usage for org.apache.commons.math3.random RandomGenerator nextDouble

List of usage examples for org.apache.commons.math3.random RandomGenerator nextDouble

Introduction

In this page you can find the example usage for org.apache.commons.math3.random RandomGenerator nextDouble.

Prototype

double nextDouble();

Source Link

Document

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

Usage

From source file:com.fpuna.preproceso.TestApacheMathLibDemo.java

/**
 * @param args//  www  .  j av a 2  s  .  c  o m
 */
public static void main(String[] args) {

    RandomGenerator randomGenerator = new JDKRandomGenerator();
    System.out.println(randomGenerator.nextInt());
    System.out.println(randomGenerator.nextDouble());

    /**
     * Descriptive Statistics like MEAN,GP,SD,MAX
    *
     */
    DescriptiveStatistics stats = new DescriptiveStatistics();
    stats.addValue(1);
    stats.addValue(2);
    stats.addValue(3);
    stats.addValue(4);
    stats.addValue(5);
    stats.addValue(6);
    stats.addValue(7);
    System.out.print("Mean : " + stats.getMean() + "\n");
    System.out.print("Standard deviation : " + stats.getStandardDeviation() + "\n");
    System.out.print("Max : " + stats.getMax() + "\n");

    /**
     * Complex number format a+bi
    *
     */
    Complex c1 = new Complex(1, 2);
    Complex c2 = new Complex(2, 3);
    System.out.print("Absolute of c1 " + c1.abs() + "\n");
    System.out.print("Addition : " + (c1.add(c2)) + "\n");
}

From source file:math.test.TestDimpleRandom.java

/**
 * Measures speed of Apache vs Colt generators
 *///from w w  w.j a va2  s.  co m
public static void main(String[] args) {
    RandomGenerator apacheGenerator = new MersenneTwister(42);
    cern.jet.random.engine.RandomEngine cernGenerator = new cern.jet.random.engine.MersenneTwister();

    final int N = 100000;
    long start, end;

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        apacheGenerator.nextDouble();
    }
    end = System.nanoTime();
    long apacheTime = end - start;

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        cernGenerator.nextDouble();
    }
    end = System.nanoTime();

    long cernTime = end - start;

    System.out.format("MersenneTwister.nextDouble() x %d apache/cern %f\n", N, (double) apacheTime / cernTime);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        BetaDistribution apacheBeta = new BetaDistribution(apacheGenerator, 1.0, 1.0);
        apacheBeta.sample();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    cern.jet.random.Beta cernBeta = new cern.jet.random.Beta(1, 1, cernGenerator);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        cernBeta.nextDouble();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    System.out.format("Beta x %d apache/cern %f\n", N, (double) apacheTime / cernTime);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        GammaDistribution apacheGamma = new GammaDistribution(apacheGenerator, 1.0, 1.0);
        apacheGamma.sample();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    cern.jet.random.Gamma cernGamma = new cern.jet.random.Gamma(1, 1, cernGenerator);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        cernGamma.nextDouble();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    System.out.format("Gamma x %d apache/cern %f\n", N, (double) apacheTime / cernTime);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        BinomialDistribution apacheBinomial = new BinomialDistribution(apacheGenerator, 1, .5);
        apacheBinomial.sample();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    cern.jet.random.Binomial cernBinomial = new cern.jet.random.Binomial(1, .5, cernGenerator);

    start = System.nanoTime();
    for (int i = N; --i >= 0;) {
        cernBinomial.nextInt();
    }
    end = System.nanoTime();
    apacheTime = end - start;

    System.out.format("Binomial x %d apache/cern %f\n", N, (double) apacheTime / cernTime);
}

From source file:com.anhth12.util.MathUtils.java

public static int binomial(RandomGenerator rng, int n, double p) {
    if ((p < 0) || (p > 1)) {
        return 0;
    }//from   w  ww  . ja va  2 s  .c  o m
    int c = 0;
    for (int i = 0; i < n; i++) {
        if (rng.nextDouble() < p) {
            c++;
        }
    }
    return c;
}

From source file:com.cloudera.oryx.common.math.SolverLoadIT.java

private static RealMatrix randomSymmetricMatrix(int dimension) {
    RandomGenerator random = RandomManager.getRandom();
    RealMatrix symmetric = new Array2DRowRealMatrix(dimension, dimension);
    for (int j = 0; j < dimension; j++) {
        // Diagonal
        symmetric.setEntry(j, j, random.nextDouble());
        for (int k = j + 1; k < dimension; k++) {
            // Off-diagonal
            double d = random.nextDouble();
            symmetric.setEntry(j, k, d);
            symmetric.setEntry(k, j, d);
        }//from w w  w  .  j  ava 2 s.  c om
    }
    return symmetric;
}

From source file:com.milaboratory.core.mutations.generator.MutationModels.java

public static NucleotideMutationModel getEmpiricalNucleotideMutationModelWithNoise(RandomGenerator rd,
        double minFactor, double maxFactor) {
    double l = maxFactor - minFactor;
    return new GenericNucleotideMutationModel(
            getEmpiricalNucleotideSubstitutionModelWithNoise(rd, minFactor, maxFactor),
            0.00522 * (minFactor + l * rd.nextDouble()), 0.00198 * (minFactor + l * rd.nextDouble()),
            rd.nextLong());/*w w w. j av  a2 s  .c  om*/
}

From source file:com.milaboratory.core.mutations.generator.SubstitutionModels.java

public static SubstitutionModel getEmpiricalNucleotideSubstitutionModelWithNoise(RandomGenerator rd,
        double minFactor, double maxFactor) {
    SubstitutionModelBuilder builder = new SubstitutionModelBuilder(4);
    double l = maxFactor - minFactor;
    builder.setProbability(A, G, 0.00267 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(A, C, 0.00009 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(A, T, 0.0019 * (minFactor + l * rd.nextDouble()));

    builder.setProbability(G, A, 0.00079 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(G, C, 0.0001 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(G, T, 0.00234 * (minFactor + l * rd.nextDouble()));

    builder.setProbability(C, A, 0.00001 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(C, G, 0.00017 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(C, T, 0.00162 * (minFactor + l * rd.nextDouble()));

    builder.setProbability(T, A, 0.00006 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(T, G, 0.00019 * (minFactor + l * rd.nextDouble()));
    builder.setProbability(T, C, 0.00119 * (minFactor + l * rd.nextDouble()));

    return builder.build();
}

From source file:com.github.rinde.rinsim.scenario.ScenarioTestUtil.java

public static Scenario create(long seed) {
    final int endTime = 3 * 60 * 60 * 1000;
    Scenario.Builder b = Scenario.builder()
            .addModel(PlaneRoadModel.supplier(new Point(0, 0), new Point(10, 10), SI.KILOMETER,
                    Measure.valueOf(50d, NonSI.KILOMETERS_PER_HOUR)))
            .addModel(DefaultPDPModel.supplier(TimeWindowPolicies.LIBERAL)).addEvents(Collections.nCopies(10,
                    new AddVehicleEvent(-1, VehicleDTO.builder().startPosition(new Point(5, 5)).build())));

    RandomGenerator rng = new MersenneTwister(seed);
    for (int i = 0; i < 20; i++) {
        long announceTime = rng.nextInt(DoubleMath.roundToInt(endTime * .8, RoundingMode.FLOOR));
        b.addEvent(new AddParcelEvent(ParcelDTO
                .builder(new Point(rng.nextDouble() * 10, rng.nextDouble() * 10),
                        new Point(rng.nextDouble() * 10, rng.nextDouble() * 10))
                .orderAnnounceTime(announceTime).pickupTimeWindow(new TimeWindow(announceTime, endTime))
                .deliveryTimeWindow(new TimeWindow(announceTime, endTime)).neededCapacity(0).build()));
    }//from  w  w  w  .j a  v a2 s  .  c o  m

    b.addEvent(new TimedEvent(PDPScenarioEvent.TIME_OUT, endTime)).scenarioLength(endTime)
            .stopCondition(new EndTimeStopCondition(endTime));

    b.addEventType(PDPScenarioEvent.ADD_DEPOT);

    return b.build();
}

From source file:edu.byu.nlp.stats.GammaDistribution.java

/**
 * self-contained gamma generator. Multiply result with scale parameter (or
 * divide by rate parameter). After Teh (npbayes).
 * /*from www.  ja va  2 s. c  o  m*/
 * Taken From knowceans.
 */
public static double sample(double shape, RandomGenerator rnd) {
    Preconditions.checkArgument(shape > 0.0);
    Preconditions.checkNotNull(rnd);

    if (shape == 1.0) {
        /* Exponential */
        return -Math.log(rnd.nextDouble());
    } else if (shape < 1.0) {
        /* Use Johnk's generator */
        double cc = 1.0 / shape;
        double dd = 1.0 / (1.0 - shape);
        while (true) {
            double xx = Math.pow(rnd.nextDouble(), cc);
            double yy = xx + Math.pow(rnd.nextDouble(), dd);
            if (yy <= 1.0) {
                // FIXME: assertion error for rr = 0.010817814317923407
                // assert yy != 0 && xx / yy > 0 : "rr = " + rr;
                // INFO: this if is a hack
                if (yy != 0 && xx / yy > 0) {
                    return -Math.log(rnd.nextDouble()) * xx / yy;
                }
            }
        }
    } else { /* rr > 1.0 */
        /* Use bests algorithm */
        double bb = shape - 1.0;
        double cc = 3.0 * shape - 0.75;
        while (true) {
            double uu = rnd.nextDouble();
            double vv = rnd.nextDouble();
            double ww = uu * (1.0 - uu);
            double yy = Math.sqrt(cc / ww) * (uu - 0.5);
            double xx = bb + yy;
            if (xx >= 0) {
                double zz = 64.0 * ww * ww * ww * vv * vv;
                assert zz > 0 && bb != 0 && xx / bb > 0;
                if ((zz <= (1.0 - 2.0 * yy * yy / xx))
                        || (Math.log(zz) <= 2.0 * (bb * Math.log(xx / bb) - yy))) {
                    return xx;
                }
            }
        }
    }
}

From source file:com.github.rinde.rinsim.pdptw.common.ScenarioTestUtil.java

/**
 * Creates a random scenario.// w  w  w  . j av a 2s  . c o m
 * @param seed The seed to use.
 * @param models Additional models (optional).
 * @return A new random scenario.
 */
public static Scenario createRandomScenario(long seed, ModelBuilder<?, ?>... models) {
    final int endTime = 3 * 60 * 60 * 1000;
    final Scenario.Builder b = Scenario.builder().addModel(RoadModelBuilders.plane())
            .addModel(DefaultPDPModel.builder()).addModels(asList(models)).addEvents(Collections.nCopies(10,
                    AddVehicleEvent.create(-1, VehicleDTO.builder().startPosition(new Point(5, 5)).build())));

    final RandomGenerator rng = new MersenneTwister(seed);
    for (int i = 0; i < 20; i++) {
        final long announceTime = rng.nextInt(DoubleMath.roundToInt(endTime * .8, RoundingMode.FLOOR));
        b.addEvent(AddParcelEvent.create(Parcel
                .builder(new Point(rng.nextDouble() * 10, rng.nextDouble() * 10),
                        new Point(rng.nextDouble() * 10, rng.nextDouble() * 10))
                .orderAnnounceTime(announceTime).pickupTimeWindow(TimeWindow.create(announceTime, endTime))
                .deliveryTimeWindow(TimeWindow.create(announceTime, endTime)).neededCapacity(0).buildDTO()));
    }

    b.addEvent(TimeOutEvent.create(endTime)).scenarioLength(endTime)
            .setStopCondition(StopConditions.limitedTime(endTime));

    return b.build();
}

From source file:edu.byu.nlp.crowdsourcing.models.meanfield.MeanFieldMomRespModelTest.java

private static MeanFieldMomRespModel buildModel(RandomGenerator rnd, int numClasses, int numAnnotators,
        int numInstances, int numFeatures) {

    // priors//from w  w w.  j  a v  a 2s  . c o  m
    double bTheta = rnd.nextDouble();
    double bMu = rnd.nextDouble();
    double cMu = rnd.nextDouble() * 10;
    double bAlpha = rnd.nextDouble();
    double cAlpha = rnd.nextDouble() * 10;
    double bPhi = rnd.nextDouble();
    PriorSpecification priors = new PriorSpecification(bTheta, bMu, cMu, bAlpha, cAlpha, bPhi, -1, false,
            numAnnotators);

    int[][][] a = new int[numInstances][numAnnotators][numClasses];
    for (int i = 0; i < numInstances; i++) {
        for (int j = 0; j < numAnnotators; j++) {
            for (int k = 0; k < numClasses; k++) {
                a[i][j][k] = rnd.nextInt(10);
            }
        }
    }
    double[][] countOfXAndF = new double[numInstances][numFeatures];
    for (int i = 0; i < numInstances; i++) {
        for (int f = 0; f < numFeatures; f++) {
            countOfXAndF[i][f] = rnd.nextDouble();
        }
    }
    double[][][] gammaParams = new double[numAnnotators][numClasses][numClasses];
    for (int j = 0; j < numAnnotators; j++) {
        CrowdsourcingUtils.initializeConfusionMatrixWithPrior(gammaParams[j], priors.getBGamma(j),
                priors.getCGamma());
    }
    Map<String, Integer> instanceIndices = Maps.newHashMap();
    for (int i = 0; i < numInstances; i++) {
        instanceIndices.put("" + i, i);
    }
    Dataset data = null;
    //    MeanFieldMomRespModel model = new MeanFieldMomRespModel(priors, a, countOfXAndF, gammaParams, instanceIndices, data, rnd);
    MeanFieldMomRespModel model = new MeanFieldMomRespModel(priors, a, gammaParams, instanceIndices, data, rnd);

    // init variables
    for (int i = 0; i < numInstances; i++) {
        for (int k = 0; k < numClasses; k++) {
            model.vars.logg[i][k] = rnd.nextDouble();
        }
        DoubleArrays.normalizeAndLogToSelf(model.vars.logg[i]);
    }
    for (int k = 0; k < numClasses; k++) {
        model.vars.pi[k] = rnd.nextDouble() * 10;
    }
    for (int j = 0; j < numAnnotators; j++) {
        for (int k = 0; k < numClasses; k++) {
            for (int k2 = 0; k2 < numClasses; k2++) {
                model.vars.nu[j][k][k2] = rnd.nextDouble() * 10;
            }
        }
    }
    for (int k = 0; k < numClasses; k++) {
        for (int f = 0; f < numFeatures; f++) {
            model.vars.lambda[k][f] = rnd.nextDouble() * 10;
        }
    }
    return model;
}