Example usage for java.util Random nextDouble

List of usage examples for java.util Random nextDouble

Introduction

In this page you can find the example usage for java.util Random nextDouble.

Prototype

public 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:eu.crisis_economics.abm.firm.io.RandomInputOutputMatrixFactory.java

@Override
public InputOutputMatrix createInputOutputMatrix() {
    final Random dice = new Random(seed);
    final int dimension = sectorNames.size();
    final double[][] data = new double[dimension][dimension];
    for (int i = 0; i < dimension; ++i)
        for (int j = 0; j < dimension; ++j)
            data[i][j] = dice.nextDouble();
    return new InputOutputMatrix(MatrixUtils.createRealMatrix(data), sectorNames);
}

From source file:com.facebook.presto.operator.aggregation.AbstractTestApproximateAggregationFunction.java

@Test
public void testCorrectnessOnUniformData() throws Exception {
    int originalDataSize = 10000;
    Random distribution = new Random(0);
    List<Number> list = new ArrayList<>();
    for (int i = 0; i < originalDataSize; i++) {
        list.add(distribution.nextDouble() * 1000);
    }/*  w  ww .j a v  a  2s. c o  m*/

    testCorrectnessOfErrorFunction(list);
}

From source file:org.canova.api.util.MathUtils.java

/**
 * Generate a uniform random number from the given rng
 *
 * @param rng the rng to use//  w  ww  .  jav  a2  s .  c o  m
 * @param min the min num
 * @param max the max num
 * @return a number uniformly distributed between min and max
 */
public static double uniform(Random rng, double min, double max) {
    return rng.nextDouble() * (max - min) + min;
}

From source file:eu.amidst.core.exponentialfamily.EF_Dirichlet.java

/**
 * {@inheritDoc}/*ww w.  j  ava 2 s  . co m*/
 */
@Override
public EF_UnivariateDistribution randomInitialization(Random random) {

    for (int i = 0; i < this.nOfStates; i++) {
        this.getNaturalParameters().set(i, 5 * random.nextDouble() + 1 + 1e-5);
    }
    fixNumericalInstability();
    this.updateMomentFromNaturalParameters();

    return this;
}

From source file:com.example.geomesa.accumulo.AccumuloQuickStart.java

static FeatureCollection createNewFeatures(SimpleFeatureType simpleFeatureType, int numNewFeatures) {
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    String id;//from  ww w  .  j  av a2 s.  c  o m
    Object[] NO_VALUES = {};
    String[] PEOPLE_NAMES = { "Addams", "Bierce", "Clemens" };
    Long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L;
    Random random = new Random(5771);
    DateTime MIN_DATE = new DateTime(2014, 1, 1, 0, 0, 0, DateTimeZone.forID("UTC"));
    Double MIN_X = -78.0;
    Double MIN_Y = -39.0;
    Double DX = 2.0;
    Double DY = 2.0;

    for (int i = 0; i < numNewFeatures; i++) {
        // create the new (unique) identifier and empty feature shell
        id = "Observation." + Integer.toString(i);
        SimpleFeature simpleFeature = SimpleFeatureBuilder.build(simpleFeatureType, NO_VALUES, id);

        // be sure to tell GeoTools explicitly that you want to use the ID you provided
        simpleFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

        // populate the new feature's attributes

        // string value
        simpleFeature.setAttribute("Who", PEOPLE_NAMES[i % PEOPLE_NAMES.length]);

        // long value
        simpleFeature.setAttribute("What", i);

        // location:  construct a random point within a 2-degree-per-side square
        double x = MIN_X + random.nextDouble() * DX;
        double y = MIN_Y + random.nextDouble() * DY;
        Geometry geometry = WKTUtils.read("POINT(" + x + " " + y + ")");

        // date-time:  construct a random instant within a year
        simpleFeature.setAttribute("Where", geometry);
        DateTime dateTime = MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR));
        simpleFeature.setAttribute("When", dateTime.toDate());

        // another string value
        // "Why"; left empty, showing that not all attributes need values

        // accumulate this new feature in the collection
        featureCollection.add(simpleFeature);
    }

    return featureCollection;
}

From source file:com.example.geomesa.cassandra.CassandraQuickStart.java

static FeatureCollection createNewFeatures(SimpleFeatureType simpleFeatureType, int numNewFeatures) {
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    String id;//from  w w w . java 2  s  .  c  o  m
    Object[] NO_VALUES = {};
    String[] PEOPLE_NAMES = { "Addams", "Bierce", "Clemens" };
    Long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L;
    Random random = new Random(5771);
    ZonedDateTime MIN_DATE = ZonedDateTime.of(2014, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
    Double MIN_X = -78.0;
    Double MIN_Y = -39.0;
    Double DX = 2.0;
    Double DY = 2.0;

    for (int i = 0; i < numNewFeatures; i++) {
        // create the new (unique) identifier and empty feature shell
        id = "Observation." + Integer.toString(i);
        SimpleFeature simpleFeature = SimpleFeatureBuilder.build(simpleFeatureType, NO_VALUES, id);

        // be sure to tell GeoTools explicitly that you want to use the ID you provided
        simpleFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

        // populate the new feature's attributes

        // string value
        simpleFeature.setAttribute("Who", PEOPLE_NAMES[i % PEOPLE_NAMES.length]);

        // long value
        simpleFeature.setAttribute("What", i);

        // location:  construct a random point within a 2-degree-per-side square
        double x = MIN_X + random.nextDouble() * DX;
        double y = MIN_Y + random.nextDouble() * DY;
        Geometry geometry = WKTUtils.read("POINT(" + x + " " + y + ")");

        // date-time:  construct a random instant within a year
        simpleFeature.setAttribute("Where", geometry);
        ZonedDateTime dateTime = MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR));
        simpleFeature.setAttribute("When", Date.from(dateTime.toInstant()));

        // another string value
        // "Why"; left empty, showing that not all attributes need values

        // accumulate this new feature in the collection
        featureCollection.add(simpleFeature);
    }

    return featureCollection;
}

From source file:org.apache.sysml.runtime.matrix.data.LibMatrixDatagen.java

public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity)
        throws DMLRuntimeException {
    long lnumBlocks = (long) (Math.ceil((double) nrow / brlen) * Math.ceil((double) ncol / bclen));

    //sanity check max number of blocks (before cast to avoid overflow)
    if (lnumBlocks > Integer.MAX_VALUE) {
        throw new DMLRuntimeException("A random matrix of size [" + nrow + "," + ncol + "] can not be created. "
                + "Number of blocks (" + lnumBlocks
                + ") exceeds the maximum integer size. Try to increase the block size.");
    }//from   ww  w.  ja  v a 2  s. com

    // NOTE: Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
    // TODO: Instead of using the expected value, NNZ should be random variable 

    int numBlocks = (int) lnumBlocks;
    long nnz = (long) Math.ceil(nrow * (ncol * sparsity));

    // Compute block-level NNZ
    long[] ret = new long[numBlocks];

    if (nnz < numBlocks) {
        // Ultra-sparse matrix

        // generate the number of blocks with at least one non-zero
        // = a random number between [1,nnz]
        Random runif = new Random(System.nanoTime());
        int numNZBlocks = 1;
        if (nnz - 1 > 0)
            numNZBlocks += runif.nextInt((int) (nnz - 1)); // To avoid exception from random.nextInt(0) 

        // distribute non-zeros across numNZBlocks

        // compute proportions for each nzblock 
        // - divide (0,1] interval into numNZBlocks portions of random size
        double[] blockNNZproportions = new double[numNZBlocks];

        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks - 1; i++) {
            blockNNZproportions[i] = runif.nextDouble();
        }
        blockNNZproportions[numNZBlocks - 1] = 1;
        // sort the values in ascending order
        Arrays.sort(blockNNZproportions);

        // compute actual number of non zeros per block according to proportions
        long actualnnz = 0;
        int bid;
        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks; i++) {
            bid = -1;
            do {
                bid = runif.nextInt(numBlocks);
            } while (ret[bid] != 0);

            double prop = (i == 0 ? blockNNZproportions[i]
                    : (blockNNZproportions[i] - blockNNZproportions[i - 1]));
            ret[bid] = (long) Math.floor(prop * nnz);
            actualnnz += ret[bid];
        }

        // Code to make sure exact number of non-zeros are generated
        while (actualnnz < nnz) {
            bid = runif.nextInt(numBlocks);
            ret[bid]++;
            actualnnz++;
        }
    } else {
        int bid = 0;

        for (long r = 0; r < nrow; r += brlen) {
            long curBlockRowSize = Math.min(brlen, (nrow - r));
            for (long c = 0; c < ncol; c += bclen) {
                long curBlockColSize = Math.min(bclen, (ncol - c));
                ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity);
                bid++;
            }
        }
    }
    return ret;
}

From source file:uk.ac.imperial.presage2.core.simulator.DeclaredParameterTest.java

@Test
public void testTypes()
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Random rnd = new Random();
    TestSource source = new TestSource();
    String[] names = { "testInt", "testDouble", "testBool", "testEnum", "testString" };
    Object[] values = { rnd.nextInt(), rnd.nextDouble(), rnd.nextBoolean(), EnumTest.values()[rnd.nextInt(3)],
            RandomStringUtils.randomAlphanumeric(rnd.nextInt(500)) };
    for (int i = 0; i < names.length; i++) {
        Field f = TestSource.class.getField(names[i]);
        Parameter a1 = f.getAnnotation(Parameter.class);
        DeclaredParameter test = new DeclaredParameter(a1, source, f);

        test.setValue(values[i].toString());
        assertEquals(values[i], f.get(source));
        assertEquals(names[i], test.name);
        assertFalse(test.optional);//from www  . ja va  2s . c o  m
    }
}

From source file:tools.PerformanceTest.java

@Test
public void testGetFeatures() throws LayerException, GeomajasException {
    int nrFeatures = 0;
    int nrCoords = 0;
    Random rand = new Random();
    System.out.println("Starting...");
    Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
    for (int i = 0; i <= 100; i++) {
        Filter bbox = filterService.createBboxFilter(crs, new Envelope(637470 + rand.nextDouble(),
                637742 + rand.nextDouble(), 5461219 + rand.nextDouble(), 5465601 + rand.nextDouble()),
                "geometry");
        List<InternalFeature> features = vectorLayerService.getFeatures(
                KtunaxaConstant.LAYER_REFERENCE_BASE_SERVER_ID, crs, bbox, referenceBaseStyleInfo,
                VectorLayerService.FEATURE_INCLUDE_ALL);
        nrFeatures += features.size();//from   w ww .  j  ava 2 s . c o  m
        for (InternalFeature internalFeature : features) {
            nrCoords += internalFeature.getGeometry().getCoordinates().length;
        }
        System.out.println(nrFeatures + " features, " + nrCoords + " coordinates.");
    }
}

From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.LineSearchTest.java

private void testOptimizationWithDomainBounds(final int numberOfDimensions, final double[] lowerDomainBounds,
        final double[] upperDomainBounds) {
    final MultivariateFunction meritFunction = new MultivariateFunction() {
        @Override/* ww w.  j a va  2s  . c  o m*/
        public double value(final double[] x) {
            double result = 0.;
            for (int i = 0; i < numberOfDimensions; ++i)
                result += -x[i] * x[i];
            return result;
        }
    };
    Random dice = new Random();
    double[] startingPoint = new double[numberOfDimensions], vectorDirection = new double[numberOfDimensions];
    for (int i = 0; i < numberOfDimensions; ++i)
        vectorDirection[i] = dice.nextDouble() - .5;
    LineSearchResult solution = BrentLineSearch.doLineSearch(meritFunction, startingPoint, vectorDirection,
            upperDomainBounds, lowerDomainBounds);
    boolean solutionIsOnDomainBoundary = false;
    for (int i = 0; i < numberOfDimensions; ++i) {
        final double solutionPoint = solution.getSolutionPoint()[i];
        System.out.printf("Coordinate %4d: distance from lower bound: %16.10g, from upper bound: %16.10g\n", i,
                solutionPoint - lowerDomainBounds[i], upperDomainBounds[i] - solutionPoint);
        if (Math.abs(solutionPoint - upperDomainBounds[i]) < 1.e-8
                || Math.abs(solutionPoint - lowerDomainBounds[i]) < 1.e-8)
            solutionIsOnDomainBoundary = true;
    }
    Assert.assertTrue(solutionIsOnDomainBoundary);
}