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:wa.was.blastradius.managers.TNTEffectsManager.java

public List<Location> getRandomLocation(Location center, int radius, int amount) {
    Random rand = new Random();
    List<Location> locations = new ArrayList<Location>();
    for (int i = 1; i <= amount; i++) {
        double angle = rand.nextDouble() * 360;
        double x = center.getX() + (rand.nextDouble() * radius * Math.cos(Math.toRadians(angle)));
        double y = center.getY() + (rand.nextDouble() * radius * Math.cos(Math.toRadians(angle)));
        double z = center.getZ() + (rand.nextDouble() * radius * Math.sin(Math.toRadians(angle)));
        Location relLoc = new Location(center.getWorld(), x, y, z);
        Location location = center.getWorld().getHighestBlockAt(relLoc).getLocation();
        locations.add(location);//from w  ww  . j a va2s .c  om
    }
    return locations;
}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate) {
    Random rnd = new Random();
    BufferedReader br = null;// w w w .jav a  2s. c  o  m
    LocalDateTime st = null;

    try {
        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();
        //PrintWriter sckt_out = new PrintWriter(os, true);

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        while (cnt < numEvents) {
            cnt += 1;
            LocalDateTime ct = LocalDateTime.now();
            String dtg = ct.toString();
            Double lat = 180 * rnd.nextDouble() - 90.0;
            Double lon = 360 * rnd.nextDouble() - 180.0;
            String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + ","
                    + lat.toString() + "\"," + cnt.toString() + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            if (cnt % 1000 == 0) {
                //System.out.println(cnt);
            }

            //sckt_out.write(line);
            os.write(line.getBytes());
            os.flush();

        }

        if (st != null) {
            LocalDateTime et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        //sckt_out.close();
        sckt.close();
        os = null;
        //sckt_out = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:com.jins_meme.bridge.VDJMenuFragment.java

double rand3(double x, double a, double b, double c) {
    double y = 0.0;
    Random r = new Random();

    if (x < 1.0 / 3.0) {
        if (r.nextDouble() < a) {
            y = x;/*from  w ww  . j a  v  a2 s  .co  m*/
        } else {
            y = 2.0 * x + 1.0 / 3.0;
        }
    } else if (x >= 1.0 / 3.0 && x < 2.0 / 3.0) {
        if (r.nextDouble() < b) {
            y = x;
        } else {
            if (x < 1.0 / 2.0) {
                y = 2.0 * x - 2.0 / 3.0;
            } else {
                y = 2.0 * x - 1.0 / 3.0;
            }
            y = 2.0 * x + 1.0 / 3.0;
        }
    } else if (x >= 2.0 / 3.0 && x < 1.0) {
        if (r.nextDouble() < c) {
            y = x;
        } else {
            y = 2.0 * x - 4.0 / 3.0;
        }
    }

    return y;
}

From source file:org.n52.ifgicopter.spf.input.DummyInputPlugin.java

@Override
public void init() throws Exception {
    this.gui = new ModuleGUI();
    JPanel panel = new JPanel(new FlowLayout());
    JLabel label = new JLabel("<html><h1>Dummy InputPlugin</h1><p>Running time: " + LOOP_SEC
            + " seconds with a new value interval of " + this.sleeptime
            + " milliseconds.</p><p></p><p>Once started, you cannot stop it.</p></html>");
    panel.add(label);/*  w  w  w  .j a va 2s .co  m*/

    final JButton startbut = new JButton("Start");
    startbut.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            start();
            startbut.setEnabled(false);
        }
    });
    panel.add(startbut);

    this.gui.setGui(panel);

    new Thread(new Runnable() {

        @Override
        public void run() {
            while (!DummyInputPlugin.this.initialized) {
                try {
                    Thread.sleep(THREAD_SLEEP_TIME_MASTER_WHILE_LOOP);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                while (true) {
                    if (DummyInputPlugin.this.running) {

                        innerRun();

                    } else {
                        try {
                            Thread.sleep(THREAD_SLEEP_TIME_MASTER_WHILE_LOOP);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("error in run()", e);
            }
        }

        private void innerRun() {
            double altDelta = 0.5;
            int humicount = 0;
            Random rand = new Random();

            Map<String, Object> posData = null;
            Map<String, Object> sensorData = null;

            long start = System.currentTimeMillis();
            posData = new HashMap<String, Object>();

            /*
             * do loop of LOOP_SEC seconds
             */
            log.debug("starting time series for " + LOOP_SEC + " seconds.");
            while (System.currentTimeMillis() - start < LOOP_SEC * 1000) {

                posData.put("time", Long.valueOf(System.currentTimeMillis()));
                posData.put("latitude", Double.valueOf(52.0 + rand.nextDouble() * 0.0025));
                posData.put("longitude", Double.valueOf(7.0 + rand.nextDouble() * 0.0025));
                posData.put("altitude", Double.valueOf((altDelta * humicount) + 34.0 + rand.nextDouble() * 7));

                DummyInputPlugin.this.populateNewData(posData);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    log.error(e);
                }

                /*
                 * now with humidity
                 */
                sensorData = new HashMap<String, Object>();

                sensorData.put("time", Long.valueOf(System.currentTimeMillis()));
                sensorData.put("humidity", Double.valueOf(70.2 + (rand.nextInt(200) / 10.0)));
                sensorData.put("humiditay", Double.valueOf(70.2 + (rand.nextInt(200) / 10.0)));
                sensorData.put("temperature", Double.valueOf(20.0 + (rand.nextInt(40) / 10.0)));
                humicount++;

                DummyInputPlugin.this.populateNewData(sensorData);

                try {
                    Thread.sleep(DummyInputPlugin.this.sleeptime);
                } catch (InterruptedException e) {
                    log.error(e);
                }

            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e);
            }

            posData.put("time", Long.valueOf(System.currentTimeMillis()));
            DummyInputPlugin.this.populateNewData(posData);

            log.info("humicount=" + humicount);

            // just one run!
            stop();
        }

    }).start();

    this.initialized = true;
}

From source file:enumj.EnumeratorTest.java

@Test
public void testAllMatch() {
    System.out.println("allMatch");
    EnumeratorGenerator.generators().limit(100).map(g -> g.enumerator()).map(e -> e.map(x -> x * x))
            .forEach(e -> {/*from  ww w.  j a v a  2s.  co m*/
                assertTrue(e.allMatch(x -> x >= 0));
            });
    final Random rnd = new Random(100);
    EnumeratorGenerator.generators().limit(100).map(g -> g.enumerator())
            .map(e -> e.append(-1.0, -0.5, 0.0, 0.25, 0.75))
            .map(e -> e.map((Double d) -> Pair.of(d, rnd.nextDouble()))
                    .sorted((p1, p2) -> Double.compare(p1.getRight(), p2.getRight())).map(p -> p.getLeft()))
            .map(e -> e.map(x -> x * x)).forEach(e -> {
                assertFalse(e.allMatch(x -> x > 1));
            });
}

From source file:org.apache.beam.sdk.io.synthetic.SyntheticOptions.java

public KV<byte[], byte[]> genKvPair(long seed) {
    Random random = new Random(seed);

    byte[] key = new byte[(int) keySizeBytes];
    // Set the user-key to contain characters other than ordered-code escape characters
    // (specifically '\0' or '\xff'). The user-key is encoded into the shuffle-key using
    // ordered-code, and the shuffle-key is then checked for size limit violations. A user-key
    // consisting of '\0' keySizeBytes would produce a shuffle-key encoding double in size,
    // which would go over the shuffle-key limit (see b/28770924).
    for (int i = 0; i < keySizeBytes; ++i) {
        key[i] = 42;//  www. j ava 2 s.c o m
    }
    // Determines whether to generate hot key or not.
    if (random.nextDouble() < hotKeyFraction) {
        // Generate hot key.
        // An integer is randomly selected from the range [0, numHotKeys-1] with equal probability.
        int randInt = random.nextInt((int) numHotKeys);
        ByteBuffer.wrap(key).putInt(hashFunction().hashInt(randInt).asInt());
    } else {
        // Note that the random generated key might be a hot key.
        // But the probability of being a hot key is very small.
        random.nextBytes(key);
    }

    byte[] val = new byte[(int) valueSizeBytes];
    random.nextBytes(val);
    return KV.of(key, val);
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSpeed2Helper(LineReader lr, RandomAccessFile ra, boolean warmup) throws Exception {
    int seeks = 10000;
    Profiler profiler = new Profiler();
    profiler.setExpectedTotal(seeks);//  ww w  .j a va2  s . c  om
    profiler.setBpsSpan(1000);
    long size = lr.length();
    Random random = new Random();

    profiler.reset();
    for (int i = 0; i < seeks; i++) {
        long pos = Math.round(Math.floor(random.nextDouble() * (size - 6)));
        try {
            lr.seek(pos);
        } catch (EOFException e) {
            fail("Reached EOF at position " + pos);
        }
        lr.readInt();
        profiler.beat();
    }
    if (!warmup) {
        System.out.println("Seeked and read an int " + seeks + " times with LR " + "on a file of size " + size
                + " at " + Math.round(profiler.getBps(true)) + " seeks/second");
    }

    profiler.reset();
    for (int i = 0; i < seeks; i++) {
        long pos = Math.round(Math.floor(random.nextDouble() * (size - 6)));
        try {
            ra.seek(pos);
        } catch (EOFException e) {
            fail("Reached EOF at position " + pos);
        }
        ra.readInt();
        profiler.beat();
    }
    if (!warmup) {
        System.out.println("Seeked and read an int " + seeks + " times with RA " + "on a file of size " + size
                + " at " + Math.round(profiler.getBps(true)) + " seeks/second");
    }
}

From source file:org.rhq.metrics.simulator.Simulator.java

/**
 * Run a sequential simulation where metrics insertion and aggregation run
 * in a single thread in sequence. The progression of time
 * is managed by the simulation. This guarantees that
 * the number of insertions and sequence of events takes
 * place in order irrespective of host limitations.
 *///from w ww .  j  av  a2  s. c om
private void runSequentialSimulation(SimulationPlan plan) throws Throwable {
    this.initializeMetricsServer(plan);

    Random random = new Random();
    long timestamp = plan.getDateTimeService().nowInMillis();
    long endOfSimulation = timestamp + 24L * 60 * 60 * 1000 * plan.getSimulationTime();
    int numberOfMetrics = plan.getBatchSize() * plan.getNumMeasurementCollectors();

    Set<MeasurementDataNumeric> data = new HashSet<MeasurementDataNumeric>(plan.getBatchSize());

    int lastAggregationHour = new DateTime(timestamp).getHourOfDay();

    for (; timestamp < endOfSimulation; timestamp += 30 * 1000) {
        DateTime currentTime = new DateTime(timestamp);

        data.clear();
        for (int i = 0; i < numberOfMetrics; ++i) {
            data.add(new MeasurementDataNumeric(timestamp, i, random.nextDouble()));
        }

        WaitForRawInserts waitForRawInserts = new WaitForRawInserts(data.size());
        metricsServer.addNumericData(data, waitForRawInserts);
        waitForRawInserts.await("Failed to insert raw data at time: " + timestamp);

        if (currentTime.getHourOfDay() != lastAggregationHour) {
            lastAggregationHour = currentTime.getHourOfDay();
            metricsServer.calculateAggregates();
        }
    }

    metricsServer.shutdown();
    log.info("Simulation has completed. Initiating shutdown...");
    shutdown(0);
}

From source file:org.n52.ifgicopter.spf.input.TimeSeriesSimulation.java

@Override
public void init() throws Exception {
    this.gui = new ModuleGUI();
    JPanel panel = new JPanel(new FlowLayout());
    JLabel label = new JLabel("<html><h1>Time Series Simulation</h1><p>Running time: " + LOOP_SEC
            + " seconds with a new value interval of " + this.sleeptime
            + " milliseconds.</p><p></p><p>Go to <b>Menu -> Start</b> to start the time series. Once started, you cannot stop it (<b>Menu -> Stop</b> does not work!).</p></html>");
    panel.add(label);/* w w w.j  a v  a 2  s  .  co m*/
    this.gui.setGui(panel);

    JMenu menu = new JMenu();
    JMenuItem start = new JMenuItem("Start");
    start.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    start();
                }
            });
        }
    });
    menu.add(start);
    JMenuItem stop = new JMenuItem("Stop");
    stop.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    stop();
                }
            });
        }
    });
    menu.add(stop);
    this.gui.setMenu(menu);

    new Thread(new Runnable() {

        @Override
        public void run() {
            while (!TimeSeriesSimulation.this.initialized) {
                try {
                    Thread.sleep(THREAD_SLEEP_TIME_MASTER_WHILE_LOOP);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                while (true) {
                    if (TimeSeriesSimulation.this.running) {

                        innerRun();

                    } else {
                        try {
                            Thread.sleep(THREAD_SLEEP_TIME_MASTER_WHILE_LOOP);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("error in run()", e);
            }
        }

        private void innerRun() {
            int humicount = 0;
            Random rand = new Random();

            Map<String, Object> posData = null;
            Map<String, Object> sensorData = null;

            long starttime = System.currentTimeMillis();
            posData = new HashMap<String, Object>();

            /*
             * do loop of LOOP_SEC seconds
             */
            log.debug("starting time series for " + LOOP_SEC + " seconds.");
            while (System.currentTimeMillis() - starttime < LOOP_SEC * 1000) {

                posData.put("time", Long.valueOf(System.currentTimeMillis()));
                posData.put("latitude", Double.valueOf(52.0 + rand.nextDouble() * 0.0025));
                posData.put("longitude", Double.valueOf(7.0 + rand.nextDouble() * 0.0025));
                posData.put("altitude", Double.valueOf(34.0 + rand.nextDouble() * 7));

                TimeSeriesSimulation.this.populateNewData(posData);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    log.error(e);
                }

                /*
                 * now with humidity
                 */
                sensorData = new HashMap<String, Object>();

                sensorData.put("time", Long.valueOf(System.currentTimeMillis()));
                sensorData.put("humidity", Double.valueOf(70.2 + (rand.nextInt(200) / 10.0)));
                sensorData.put("humiditay", Double.valueOf(70.2 + (rand.nextInt(200) / 10.0)));
                sensorData.put("temperature", Double.valueOf(20.0 + (rand.nextInt(40) / 10.0)));
                humicount++;

                TimeSeriesSimulation.this.populateNewData(sensorData);

                try {
                    Thread.sleep(TimeSeriesSimulation.this.sleeptime);
                } catch (InterruptedException e) {
                    log.error(e);
                }

            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e);
            }

            posData.put("time", Long.valueOf(System.currentTimeMillis()));
            TimeSeriesSimulation.this.populateNewData(posData);

            log.info("humicount=" + humicount);

            // just one run!
            stop();
        }

    }).start();

    this.initialized = true;
}

From source file:com.linkedin.pinot.query.transform.TransformGroupByTest.java

/**
 * Helper method to build a segment with one dimension column containing values
 * from {@link #_dimensionValues}, and one metric column.
 *
 * Also builds the expected group by result as it builds the segments.
 *
 * @param segmentDirName Name of segment directory
 * @param segmentName Name of segment//from www  . j  a v  a2s .  c o  m
 * @param schema Schema for segment
 * @return Schema built for the segment
 * @throws Exception
 */
private RecordReader buildSegment(String segmentDirName, String segmentName, Schema schema) throws Exception {

    SegmentGeneratorConfig config = new SegmentGeneratorConfig(schema);
    config.setOutDir(segmentDirName);
    config.setFormat(FileFormat.AVRO);
    config.setTableName(TABLE_NAME);
    config.setSegmentName(segmentName);

    Random random = new Random(RANDOM_SEED);
    long currentTimeMillis = System.currentTimeMillis();

    // Divide the day into fixed parts, and decrement time column value by this delta, so as to get
    // continuous days in the input. This gives about 10 days per 10k rows.
    long timeDelta = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) / 1000;

    final List<GenericRow> data = new ArrayList<>();
    int numDimValues = _dimensionValues.length;

    for (int row = 0; row < NUM_ROWS; row++) {
        HashMap<String, Object> map = new HashMap<>();

        map.put(DIMENSION_NAME, _dimensionValues[random.nextInt(numDimValues)]);
        map.put(METRIC_NAME, random.nextDouble());

        map.put(TIME_COLUMN_NAME, currentTimeMillis);
        currentTimeMillis -= timeDelta;

        GenericRow genericRow = new GenericRow();
        genericRow.init(map);
        data.add(genericRow);
    }

    SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
    RecordReader reader = new TestUtils.GenericRowRecordReader(schema, data);
    driver.init(config, reader);
    driver.build();

    LOGGER.info("Built segment {} at {}", segmentName, segmentDirName);
    return reader;
}