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:org.apache.hadoop.hive.llap.TestRow.java

@Test
public void testUsage() {
    Schema schema = createTestSchema();
    Row row = new Row(schema);

    Random rand = new Random();
    int iterations = 100;
    for (int idx = 0; idx < iterations; ++idx) {
        // Set the row values
        boolean isNullCol0 = (rand.nextDouble() <= 0.25);
        String col0 = RandomStringUtils.random(10);
        row.setValue(0, isNullCol0 ? null : col0);

        boolean isNullCol1 = (rand.nextDouble() <= 0.25);
        Integer col1 = Integer.valueOf(rand.nextInt());
        row.setValue(1, isNullCol1 ? null : col1);

        // Validate the row values
        if (isNullCol0) {
            assertTrue(row.getValue(0) == null);
            assertTrue(row.getValue("col0") == null);
        } else {/*  w  ww  .  j  a  v a  2  s .  com*/
            assertTrue(row.getValue(0) != null);
            assertEquals(col0, row.getValue(0));
            assertEquals(col0, row.getValue("col0"));
        }

        if (isNullCol1) {
            assertTrue(row.getValue(1) == null);
            assertTrue(row.getValue("col1") == null);
        } else {
            assertTrue(row.getValue(1) != null);
            assertEquals(col1, row.getValue(1));
            assertEquals(col1, row.getValue("col1"));
        }
    }
}

From source file:com.jjoe64.graphview_demos.fragments.AddSeriesAtRuntime.java

private DataPoint[] generateData() {
    Random rand = new Random();
    int count = 30;
    DataPoint[] values = new DataPoint[count];
    for (int i = 0; i < count; i++) {
        double x = i;
        double f = rand.nextDouble() * 0.15 + 0.3;
        double y = Math.sin(i * f + 2) + rand.nextDouble() * 0.3;
        DataPoint v = new DataPoint(x, y);
        values[i] = v;//from w  w  w .  j a  v a  2 s.c  o m
    }
    return values;
}

From source file:org.deeplearning4j.clustering.kdtree.KDTreeTest.java

@Test
public void testNN() {
    int n = 10;/*  www.j  a  v a 2  s  . co m*/

    // make a KD-tree of dimension {#n}
    KDTree kdTree = new KDTree(n);
    for (int i = -1; i < n; i++) {
        // Insert a unit vector along each dimension
        List<Double> vec = new ArrayList<>(n);
        // i = -1 ensures the origin is in the Tree
        for (int k = 0; k < n; k++) {
            vec.add((k == i) ? 1.0 : 0.0);
        }
        INDArray indVec = Nd4j.create(Nd4j.createBuffer(Doubles.toArray(vec)));
        kdTree.insert(indVec);
    }
    Random rand = new Random();

    // random point in the Hypercube
    List<Double> pt = new ArrayList(n);
    for (int k = 0; k < n; k++) {
        pt.add(rand.nextDouble());
    }
    Pair<Double, INDArray> result = kdTree.nn(Nd4j.create(Nd4j.createBuffer(Doubles.toArray(pt))));

    // Always true for points in the unitary hypercube
    assertTrue(result.getKey() < Double.MAX_VALUE);

}

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

/**
  * Generate a step function with discontinuities at 
  * random points in the unit interval./* ww  w.java2 s  . c om*/
  */
public StepResponseFunction(final BoundedUnivariateFunction existingResponseFunction) {
    super(new SimpleDomainBounds(0., existingResponseFunction.getMaximumInDomain()));
    Random random = new Random();
    int numSteps = random.nextInt(10) + 2;
    double[] stepCoordinates = new double[numSteps];
    for (int i = 0; i < numSteps; ++i)
        stepCoordinates[i] = random.nextDouble() / existingResponseFunction.getMaximumInDomain();
    Arrays.sort(stepCoordinates);
    initCommon(existingResponseFunction, stepCoordinates);
}

From source file:com.example.geomesa.hbase.HBaseQuickStart.java

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

    String id;//from w  w w .  j  a v  a2  s .co 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 = -79.5;
    Double MIN_Y = 37.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

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

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

        // Where: 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$.MODULE$.read("POINT(" + x + " " + y + ")");
        simpleFeature.setAttribute("Where", geometry);

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

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

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

    return featureCollection;
}

From source file:pl.mg6.newmaps.demo.AddOnlyVisibleMarkersExampleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.many_markers_example);

    final GoogleMap map = GoogleMapHelper.getMap(this, R.id.many_markers_map);

    final List<LatLng> positions = new ArrayList<LatLng>();

    Random r = new Random();

    long start = SystemClock.uptimeMillis();
    for (int i = 0; i < ManyMarkersExampleActivity.MARKERS_COUNT; i++) {
        LatLng position = new LatLng((r.nextDouble() - 0.5) * 170.0, (r.nextDouble() - 0.5) * 360.0);
        positions.add(position);//w  w  w . j ava2  s. co m
    }
    long end = SystemClock.uptimeMillis();
    Log.w(TAG, "generate time: " + (end - start));

    map.setOnCameraChangeListener(new OnCameraChangeListener() {

        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            long start = SystemClock.uptimeMillis();
            int count = 0;
            Projection projection = map.getProjection();
            LatLngBounds bounds = projection.getVisibleRegion().latLngBounds;
            for (int i = positions.size() - 1; i >= 0; i--) {
                LatLng position = positions.get(i);
                if (bounds.contains(position)) {
                    map.addMarker(new MarkerOptions().position(position));
                    positions.remove(i);
                    count++;
                }
            }
            long end = SystemClock.uptimeMillis();
            Log.w(TAG, "addMarkers time: " + (end - start) + ", added: " + count);
        }
    });
}

From source file:com.insightml.math.distributions.DiscreteDistribution.java

@Override
public T sample(final Random random) {
    if (map.size() == 1) {
        return map.keySet().iterator().next();
    }//w  w w . j a v a2s. c  o  m
    final double rand = random.nextDouble();
    double sum = 0;
    for (final Entry<T, Double> entry : map.entrySet()) {
        sum += entry.getValue();
        if (rand <= sum) {
            return entry.getKey();
        }
    }
    throw new IllegalStateException();
}

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

/**
 * {@inheritDoc}/*from  www . j ava 2 s.  c  o m*/
 */
@Override
public EF_UnivariateDistribution randomInitialization(Random random) {

    double randomVar = random.nextDouble() * 2 + 1 + 0.01;

    double alpha = 10;
    double beta = randomVar * alpha;
    double mean = random.nextGaussian() * 10;
    double var = random.nextDouble() * 10 + 1;
    double precision = 1 / var;

    naturalParameters.set(EF_JointNormalGamma.MU_GAMMA, mean * precision);
    naturalParameters.set(EF_JointNormalGamma.MUSQUARE_GAMMA, -0.5 * precision);
    naturalParameters.set(EF_JointNormalGamma.GAMMA, -beta - 0.5 * precision * mean * mean);
    naturalParameters.set(EF_JointNormalGamma.LOGGAMMA, alpha - 0.5);

    this.fixNumericalInstability();
    this.updateMomentFromNaturalParameters();

    return this;
}

From source file:com.insightml.data.samples.AbstractSamples.java

@Override
public final ISamples<S, E> sampleFeatures(final double ratio, final Random random) {
    if (ratio >= 1) {
        return this;
    }/*from www. j a  v a  2s  .  c o m*/
    final boolean[] keep = new boolean[numFeatures()];
    for (int i = 0; i < keep.length; ++i) {
        keep[i] = random.nextDouble() <= ratio;
    }
    return filterFeatures(keep);
}

From source file:dataGen.DataGen.java

/**
 * Creates anti-correlated Test-Data with the specified Seed
 * The resulting Data is stored in the resources Folder.
 * @param dimensions/*from www .  j  a va 2  s  .  c  o m*/
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @param gaussianData
 *       Should we create gaussian distributed Data?
 *       if false: uniform distributed Data will get created.
 * @param std
 *       standard deviation value
 * @param center
 *       center of the distribution
 * @param saveData
 *       should the Data get Saved?
 * @param seed
 *       the seed for the Random Generations
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static CustomRealMatrix genAntiCorrData(int dimensions, int rowCount, boolean gaussianData, float std,
        float center, boolean saveData, long seed) throws IOException {
    File file = null;
    // Generate the Export Files
    if (gaussianData) {
        logger.info("Generating gaussian anti-correlated Data with " + rowCount + " Tuples in " + dimensions
                + " dimensions");
        if (saveData)
            file = new File("src/main/resources/anticorr-gaussian-" + rowCount + "-" + dimensions + ".dat");
    } else {
        logger.info("Generating uniform anti-correlated Data with " + rowCount + " Tuples in " + dimensions
                + "dimensions");
        if (saveData)
            file = new File("src/main/resources/anticorr-normal-" + rowCount + "-" + dimensions + ".dat");
    }

    Random gen = new Random(seed);
    //PearsonsCorrelation corr = new PearsonsCorrelation();
    //RealMatrix corrMatrix = null;

    // Files should be created OS/Language independent
    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
    dfs.setDecimalSeparator('.');
    NumberFormat nf = new DecimalFormat("0.000000000", dfs);

    // Create a good Start-Matrix: a (dimension x dimension) matrix which fulfills the Anti-Correlation Condition
    CustomRealMatrix values = new CustomRealMatrix(rowCount, dimensions);
    int validTupleCount = 0;

    // Create the remaining Tuples
    while (validTupleCount < rowCount) {
        boolean minimalEntryFound = false;
        double entry = 0d;
        for (int j = 0; j < dimensions; j++) {
            if (gaussianData)
                entry = std * gen.nextGaussian() + center;
            else
                entry = std * gen.nextDouble() + center;

            if (!minimalEntryFound && entry < center)
                minimalEntryFound = true;
            else if (minimalEntryFound) {
                while (entry < center) {
                    if (gaussianData)
                        entry = std * gen.nextGaussian() + center;
                    else
                        entry = std * gen.nextDouble() + center;
                }
            }
            values.setEntry(validTupleCount, j, entry);
        }
        validTupleCount = validTupleCount + 1;
    }
    logger.info(values.getRowDimension() + " entries generated");
    if (saveData) {
        Writer fw = new FileWriter(file);
        saveData(values, fw, nf);
    }

    return values;
}