Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:com.balero.models.TestDAO.java

@Transactional
public void delete(int id) {
    Session session = sessionFactory.openSession();
    Test test = new Test();
    Double n = Math.random();
    test.setId(id);//  w  ww. j  a  v a  2 s  .  c  om
    session.delete(test);
    session.flush();
    session.close();
}

From source file:org.jfree.chart.demo.SimpleIntervalXYDataset2.java

/**
 * Creates a new dataset.//w ww  . java2 s . c  o m
 * 
 * @param itemCount  the number of items to generate.
 */
public SimpleIntervalXYDataset2(final int itemCount) {

    this.xValues = new Double[itemCount];
    this.yStart = new Double[itemCount];
    this.yEnd = new Double[itemCount];

    double base = 100;
    for (int i = 1; i <= itemCount; i++) {
        this.xValues[i - 1] = new Double(i);
        base = base * (1 + (Math.random() / 10 - 0.05));
        this.yStart[i - 1] = new Double(base);
        this.yEnd[i - 1] = new Double(this.yStart[i - 1].doubleValue() + Math.random() * 30);
    }
}

From source file:org.jfree.chart.demo.XYAreaChartDemo2.java

/**
 * Creates a new demo.//from   w  w w.j  a v  a  2s. com
 *
 * @param title  the frame title.
 */
public XYAreaChartDemo2(final String title) {

    super(title);

    final TimeSeries series1 = new TimeSeries("Random 1");
    double value = 0.0;
    Day day = new Day();
    for (int i = 0; i < 200; i++) {
        value = value + Math.random() - 0.5;
        series1.add(day, value);
        day = (Day) day.next();
    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection(series1);

    final JFreeChart chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(chartPanel);

}

From source file:org.jfree.chart.demo.ChartTiming3.java

/**
 * Runs the test.//from   w w  w.  java 2  s .  co  m
 */
public void run() {

    this.finished = false;

    // create a dataset...
    final XYSeries series = new XYSeries("Random Data");
    for (int i = 0; i < 1440; i++) {
        final double x = Math.random();
        final double y = Math.random();
        series.add(x, y);
    }
    final XYDataset data = new XYSeriesCollection(series);

    // create a scatter chart...
    final boolean withLegend = true;
    final JFreeChart chart = ChartFactory.createScatterPlot("Scatter plot timing", "X", "Y", data,
            PlotOrientation.VERTICAL, withLegend, false, false);

    final XYPlot plot = chart.getXYPlot();
    plot.setRenderer(new XYDotRenderer());

    final BufferedImage image = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
    final Graphics2D g2 = image.createGraphics();
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 400, 300);

    // set up the timer...
    final Timer timer = new Timer(10000, this);
    timer.setRepeats(false);
    int count = 0;
    timer.start();
    while (!this.finished) {
        chart.draw(g2, chartArea, null, null);
        System.out.println("Charts drawn..." + count);
        if (!this.finished) {
            count++;
        }
    }
    System.out.println("DONE");

}

From source file:org.bindgen.wicket.phonebook.DataGenerator.java

private int rint(int min, int max) {
    return (int) (Math.random() * (max - min) + min);
}

From source file:com.ciphertool.genetics.algorithms.crossover.LiberalUnevaluatedCrossoverAlgorithm.java

/**
 * This crossover algorithm does a liberal amount of changes since it
 * replaces genes regardless of their begin and end sequence positions
 *///from   w  w  w  .j  av a  2 s . c om
public Chromosome performCrossover(Chromosome parentA, Chromosome parentB) {
    Chromosome child = parentA.clone();

    int childGeneIndex = 0;

    /*
     * Make sure we don't exceed parentB's index, or else we will get an
     * IndexOutOfBoundsException
     */
    while (childGeneIndex < child.getGenes().size() && childGeneIndex < parentB.getGenes().size()) {
        /*
         * Flip a coin to see if the current Gene should be replaced
         */
        if (((int) (Math.random() * 2)) == 0) {
            child.replaceGene(childGeneIndex, parentB.getGenes().get(childGeneIndex).clone());

            while (child.actualSize() < child.targetSize()) {
                child.addGene(geneListDao.findRandomGene(child, child.actualSize() - 1));
            }
        }

        childGeneIndex++;
    }

    /*
     * Trim the Chromosome in case it ends with too many sequences due to
     * the nature of this algorithm
     */
    chromosomeHelper.resizeChromosome(child);

    if (mutateDuringCrossover) {
        mutationAlgorithm.mutateChromosome(child);
    }

    // Don't return this child if it's identical to one of its parents
    if (child.equals(parentA) || child.equals(parentB)) {
        return null;
    }

    /*
     * Child is guaranteed to have at least as good fitness as its parent
     */
    return child;
}

From source file:com.reelfx.controller.LinuxController.java

@Override
public void setupExtensions() {
    //super.setupExtensions();
    try {//  w  w  w .  jav a 2s.  co m
        if (!Applet.BIN_FOLDER.exists()) {
            // delete any old versions
            for (File file : Applet.BASE_FOLDER.listFiles()) {
                if (file.getName().startsWith("bin") && file.isDirectory()) {
                    FileUtils.deleteDirectory(file);
                    if (file.exists())
                        throw new Exception("Could not delete the old native extentions!");
                }
            }
            // download an install the new one
            String url = Applet.HOST_URL + File.separator + Applet.getBinFolderName() + ".jar?"
                    + Math.random() * 10000;
            Applet.copyFolderFromRemoteJar(new URL(url), Applet.getBinFolderName());
            if (!Applet.BIN_FOLDER.exists()) {
                logger.info("Could not find native extensions at " + url + ". Trying next code base url...");
                url = Applet.CODE_BASE.toString() + File.separator + Applet.getBinFolderName() + ".jar?"
                        + Math.random() * 10000;
                Applet.copyFolderFromRemoteJar(new URL(url), Applet.getBinFolderName());
                if (!Applet.BIN_FOLDER.exists()) {
                    logger.info("Could not find native extensions at " + url
                            + ". Trying next document base url...");
                    url = Applet.DOCUMENT_BASE.toString() + File.separator + Applet.getBinFolderName() + ".jar?"
                            + Math.random() * 10000;
                    Applet.copyFolderFromRemoteJar(new URL(url), Applet.getBinFolderName());
                    if (!Applet.BIN_FOLDER.exists()) {
                        throw new IOException(
                                "Did not copy Linux extensions to the execution directory! Last url: " + url);
                    }
                }
            }
            Runtime.getRuntime().exec("chmod 755 " + Applet.BIN_FOLDER + File.separator + "ffmpeg").waitFor();
            Runtime.getRuntime().exec("chmod 755 " + Applet.BIN_FOLDER + File.separator + "ffplay").waitFor();
        }
        logger.info("Have access to execution folder: " + Applet.BIN_FOLDER.getAbsolutePath());
        setReadyStateBasedOnPriorRecording();
    } catch (Exception e) { // possibilities: MalformedURL, InterriptedException, IOException
        Applet.sendViewNotification(ViewNotifications.FATAL, new MessageNotification("Error with install",
                "Sorry, an error occurred while installing the native extensions. Please contact an admin."));
        logger.error("Could not install native extensions", e);
    }
}

From source file:baggage.BaseTestCase.java

protected byte[] makeRandomBytes(int howMany) {
    byte[] bytes = new byte[howMany];

    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) (128d * Math.random());
    }//  w  w w .j  av a2s.  co m
    return bytes;
}

From source file:UnsynchBankTest.java

public void run() {
    try {//w  w w  .  ja  v a2s . c  o  m
        while (true) {
            int toAccount = (int) (bank.size() * Math.random());
            double amount = maxAmount * Math.random();
            bank.transfer(fromAccount, toAccount, amount);
            Thread.sleep((int) (DELAY * Math.random()));
        }
    } catch (InterruptedException e) {
    }
}

From source file:com.ideabase.repository.test.api.UserServiceTest.java

/**
 * Ensure user service can authenticate user credentials.
 * Successful authentication ended with a {@code User} profile object.
 *///from  w  w w  . ja  v  a2  s . co m
public void testLogin() {
    final String userName = "veryrandom-user" + Math.random();
    final String password = DigestUtils.shaHex("password is md5");

    // create user
    final Integer userId = TestCaseRepositoryHelper.fixCreateUser(mUserService, userName, password);

    // authenticate user
    final UserCredential userCredential = new UserCredential(userName, password);

    // authenticate user.
    final Subject subject = mUserService.login(userCredential);
    // retrieve user principal.
    final RepositoryUserPrincipal principal = subject.getPrincipals(RepositoryUserPrincipal.class).iterator()
            .next();

    // verify 
    assertNotNull("Authentication failed.", subject);
    assertNotNull("Authenticated user principal is null.", principal);
    assertNotNull("Authenticated user id is not attached with principal.", principal.getId());
    LOG.debug("Subject - " + subject);
}