Returns a random double between 0 (Zero) inclusive and MAX inclusive. - Android java.util

Android examples for java.util:Random Double

Description

Returns a random double between 0 (Zero) inclusive and MAX inclusive.

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    /**//from   w  w  w .j a  v a 2s  .com
     * Returns a random double between 0 (Zero) inclusive and MAX inclusive. <br/>
     * Same as {@code getRandomDouble(0, max);} <br/>
     * See {@see RandomUtil#getRandomDouble(double, double)}
     * <br>
     * <pre>
     * getRandomDouble(90642.35133634694)      =39301.97625505765
     * </pre>
     * @param max
     *            value exclusive
     * @return an int between 0 inclusive and MAX inclusive.
     */
    public static double getRandomDouble(double max) {
        double min = 0;
        if (max < 0) {
            double temp = max;
            max = 0;
            min = temp;
        }
        return getRandomDoubleWithinRange(min, max);
    }

    /**
     * Returns a random double between MIN inclusive and MAX inclusive.
     * <pre>
     * </pre>
     * @param min
     *            value inclusive
     * @param max
     *            value inclusive
     * @return an int between 0 inclusive and MAX exclusive.
     */
    public static double getRandomDoubleWithinRange(double min, double max) {
        if (min == max) {
            return max;
        }
        if (max < min) {
            double temp = max;
            max = min;
            min = temp;
        }
        Random r = new Random();
        return min + (max - min) * r.nextDouble();
    }
}

Related Tutorials