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.hama.examples.util.VectorWritableMatrixGen.java

public static double[][] createRandomMatrix(int rows, int columns, Random rand, double rangeMin,
        double rangeMax, int precision) {

    LOG.debug("createRandomMatrix rows: " + rows + " cols: " + columns);

    final double[][] matrix = new double[rows][columns];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            matrix[i][j] = new BigDecimal(randomValue).setScale(precision, BigDecimal.ROUND_DOWN).doubleValue();
        }/*from   ww  w.j  av a2  s.c o  m*/
    }
    return matrix;
}

From source file:org.apache.hadoop.mapred.gridmix.TestFilePool.java

@BeforeClass
public static void setup() throws IOException {
    final Configuration conf = new Configuration();
    final FileSystem fs = FileSystem.getLocal(conf).getRaw();
    fs.delete(base, true);//w  w  w . ja  v  a2  s.  c  o m
    final Random r = new Random();
    final long seed = r.nextLong();
    r.setSeed(seed);
    LOG.info("seed: " + seed);
    fs.mkdirs(base);
    for (int i = 0; i < NFILES; ++i) {
        Path file = base;
        for (double d = 0.6; d > 0.0; d *= 0.8) {
            if (r.nextDouble() < d) {
                file = new Path(base, Integer.toString(r.nextInt(3)));
                continue;
            }
            break;
        }
        OutputStream out = null;
        try {
            out = fs.create(new Path(file, "" + (char) ('A' + i)));
            final byte[] b = new byte[1024];
            Arrays.fill(b, (byte) ('A' + i));
            for (int len = ((i % 13) + 1) * 1024; len > 0; len -= 1024) {
                out.write(b);
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

From source file:Main.java

/**
 * Fills the array with random doubles.  Values will be between min (inclusive) and
 * max (inclusive).//  w  w w .  j a v  a 2  s .c o m
 */
public static void genRandomDoubles(long seed, double min, double max, double array[],
        boolean includeExtremes) {
    Random r = new Random(seed);
    int minExponent = Math.min(Math.getExponent(min), 0);
    int maxExponent = Math.max(Math.getExponent(max), 0);
    if (minExponent < -6 || maxExponent > 6) {
        // Use an exponential distribution
        int exponentDiff = maxExponent - minExponent;
        for (int i = 0; i < array.length; i++) {
            double mantissa = r.nextDouble();
            int exponent = minExponent + r.nextInt(maxExponent - minExponent);
            int sign = (min >= 0) ? 1 : 1 - r.nextInt(2) * 2; // -1 or 1
            double rand = sign * mantissa * Math.pow(2.0, exponent);
            if (rand < min || rand > max) {
                continue;
            }
            array[i] = rand;
        }
    } else {
        // Use a linear distribution
        for (int i = 0; i < array.length; i++) {
            double rand = r.nextDouble();
            array[i] = min + rand * (max - min);
        }
    }
    // Seed a few special numbers we want to be sure to test.
    for (int i = 0; i < sInterestingDoubles.length; i++) {
        double d = sInterestingDoubles[i];
        if (min <= d && d <= max) {
            array[r.nextInt(array.length)] = d;
        }
    }
    array[r.nextInt(array.length)] = min;
    array[r.nextInt(array.length)] = max;
    if (includeExtremes) {
        array[r.nextInt(array.length)] = Double.NaN;
        array[r.nextInt(array.length)] = Double.POSITIVE_INFINITY;
        array[r.nextInt(array.length)] = Double.NEGATIVE_INFINITY;
        array[r.nextInt(array.length)] = Double.MIN_VALUE;
        array[r.nextInt(array.length)] = Double.MIN_NORMAL;
        array[r.nextInt(array.length)] = Double.MAX_VALUE;
        array[r.nextInt(array.length)] = -Double.MIN_VALUE;
        array[r.nextInt(array.length)] = -Double.MIN_NORMAL;
        array[r.nextInt(array.length)] = -Double.MAX_VALUE;
    }
}

From source file:info.rmarcus.birkhoffvonneumann.MatrixUtils.java

public static double[][] randomMatrix(Random r, int n) {
    double[][] toR = new double[n][n];

    for (int i = 0; i < toR.length; i++)
        for (int j = 0; j < toR[i].length; j++)
            toR[i][j] = r.nextDouble();

    return toR;/*w w w . j a v a 2  s.c  om*/
}

From source file:edu.iu.daal_naive.NaiveUtil.java

static void generateTestPoints(int numOfDataPoints, int vectorSize, int nClasses, String localInputDir,
        FileSystem fs, Path dataDir) throws IOException, InterruptedException, ExecutionException {

    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);/*from www.  j a v  a 2s.  co  m*/
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();

    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }

    // generate test points
    BufferedWriter writer = new BufferedWriter(new FileWriter(localInputDir + File.separator + "testdata"));
    Random random = new Random();

    double point = 0;
    int label = 0;
    for (int i = 0; i < numOfDataPoints; i++) {
        for (int j = 0; j < vectorSize; j++) {
            point = random.nextDouble() * 2 - 1;
            writer.write(String.valueOf(point));
            writer.write(",");
        }

        label = random.nextInt(nClasses);
        writer.write(String.valueOf(label));
        writer.newLine();
    }

    writer.close();
    System.out.println("Write test data file");

    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);

}

From source file:com.joptimizer.util.Utils.java

public static DoubleMatrix2D randomValuesMatrix(int rows, int cols, double min, double max, Long seed) {
    Random random = (seed != null) ? new Random(seed) : new Random();

    double[][] matrix = new double[rows][cols];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = min + random.nextDouble() * (max - min);
        }//w  ww . ja v  a 2  s.  c o  m
    }
    return DoubleFactory2D.dense.make(matrix);
}

From source file:ml.shifu.shifu.core.binning.DynamicBinningTest.java

public static List<NumBinInfo> createNumBinInfos(int binCnt) {
    Random rd = new Random(System.currentTimeMillis());

    List<Double> thresholds = new ArrayList<Double>(binCnt - 1);
    for (int i = 0; i < binCnt - 1; i++) {
        thresholds.add(rd.nextGaussian() * 200);
    }// w  ww .  j av a  2s. co  m

    Collections.sort(thresholds);

    List<NumBinInfo> binInfoList = NumBinInfo.constructNumBinfo(StringUtils.join(thresholds, ':'), ':');
    for (NumBinInfo binInfo : binInfoList) {
        if (rd.nextDouble() > 0.45) {
            int total = rd.nextInt() % 1000;
            int positive = (int) (total * rd.nextDouble());
            binInfo.setTotalInstCnt(total);
            binInfo.setPositiveInstCnt(positive);
        }
    }

    return binInfoList;
}

From source file:org.wso2.carbon.sample.performance.Client.java

private static void publishEvents(DataPublisher dataPublisher, long eventCount, long elapsedCount,
        long warmUpCount) {
    long counter = 0;
    Random randomGenerator = new Random();
    String streamId = "org.wso2.event.sensor.stream:1.0.0";
    long lastTime = System.currentTimeMillis();
    DecimalFormat decimalFormat = new DecimalFormat("#");

    while (counter < eventCount) {
        boolean isPowerSaveEnabled = randomGenerator.nextBoolean();
        int sensorId = randomGenerator.nextInt();
        double longitude = randomGenerator.nextDouble();
        double latitude = randomGenerator.nextDouble();
        float humidity = randomGenerator.nextFloat();
        double sensorValue = randomGenerator.nextDouble();
        Event event = new Event(streamId, System.currentTimeMillis(),
                new Object[] { System.currentTimeMillis(), isPowerSaveEnabled, sensorId,
                        "temperature-" + counter },
                new Object[] { longitude, latitude }, new Object[] { humidity, sensorValue });

        dataPublisher.publish(event);//from w ww  .j a  va2  s  . c  o m

        if ((counter > warmUpCount) && ((counter + 1) % elapsedCount == 0)) {

            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastTime;
            double throughputPerSecond = (((double) elapsedCount) / elapsedTime) * 1000;
            lastTime = currentTime;
            log.info("Sent " + elapsedCount + " sensor events in " + elapsedTime
                    + " milliseconds with total throughput of " + decimalFormat.format(throughputPerSecond)
                    + " events per second.");
        }

        counter++;
    }
}

From source file:junkProducer.java

public static DefaultFeatureCollection simjunk(final SimpleFeatureBuilder builder) {
    final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    Random rng;
    rng = new Random();
    String trainCode;/*from  w  ww.j av  a 2  s . c  o  m*/

    // add three features with static meta junk, and random point
    builder.add("Good");
    trainCode = "Train A";
    builder.add(trainCode);
    builder.add("");
    builder.add("unknown");
    builder.add(DateTime.now().toDate());
    double lon = -180 + 360 * rng.nextDouble();
    double lat = -90 + 180 * rng.nextDouble();
    builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")"));
    SimpleFeature feature = builder.buildFeature(trainCode);
    featureCollection.add(feature);

    // add three features with static meta junk, and random point
    builder.reset();
    builder.add("Good");
    trainCode = "Train B";
    builder.add(trainCode);
    builder.add("");
    builder.add("unknown");
    builder.add(DateTime.now().toDate());
    lon = -180 + 360 * rng.nextDouble();
    lat = -90 + 180 * rng.nextDouble();
    builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")"));
    SimpleFeature feature2 = builder.buildFeature(trainCode);
    featureCollection.add(feature2);

    // add three features with static meta junk, and random point
    builder.reset();
    builder.add("Good");
    trainCode = "Train C";
    builder.add(trainCode);
    builder.add("");
    builder.add("unknown");
    builder.add(DateTime.now().toDate());
    lon = -180 + 360 * rng.nextDouble();
    lat = -90 + 180 * rng.nextDouble();
    builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")"));
    SimpleFeature feature3 = builder.buildFeature(trainCode);
    featureCollection.add(feature3);

    return featureCollection;
}

From source file:org.apache.hadoop.mapred.gridmix.DebugJobProducer.java

static double[] getDistr(Random r, double mindist, int size) {
    assert 0.0 <= mindist && mindist <= 1.0;
    final double min = mindist / size;
    final double rem = 1.0 - min * size;
    final double[] tmp = new double[size];
    for (int i = 0; i < tmp.length - 1; ++i) {
        tmp[i] = r.nextDouble() * rem;
    }//from   w  ww .j  a v a2 s.  com
    tmp[tmp.length - 1] = rem;
    Arrays.sort(tmp);

    final double[] ret = new double[size];
    ret[0] = tmp[0] + min;
    for (int i = 1; i < size; ++i) {
        ret[i] = tmp[i] - tmp[i - 1] + min;
    }
    return ret;
}