The random () function in Java

Source: Internet
Author: User
Tags rand

There are two kinds of random functions in Java:

First, Java.lang.Math.Random;

Call this math.random () function to return a double with a positive sign, which is greater than or equal to 0.0 and less than 1.0, that is, the value range is [0.0,1.0] the left closed right open interval, the return value is a pseudo-random selection of the number, within that range (approximate) evenly distributed. Examples are as follows:

Package Io;import Java.util.random;public class Testrandom {public        static void Main (string[] args) {        //Case 1        System.out.println ("math.random () =" + Math.random ());//The result is a double-type value with an interval of [0.0,1.0]        int num = (int) (Math.random ( ) * 3); Be careful not to write (int) math.random (), which results in 0 because the cast        System.out.println ("num=" + num) was executed first;        /**         * Output is:         *          * math.random () =0.02909671613289655         * num=0         *          */
}
}

Second, Java.util.Random

Here are two ways to construct the random ():

Random (): Creates a new random number generator.

Random (Long Seed): Creates a new random number generator with a single long seed.

We can specify the seed when constructing the Random object (specify what the seed will do here, and then look down), such as: random r1 = new random (20);

or the default number of milliseconds for the current system time as a seed number: random r1 = new Random ();

It is necessary to note that when you create a random object you can give any number of valid seed numbers, the seed number is only the origin number of the random algorithm, and the interval of the generated random number has no relation. As in the following Java code:

Random Rand =new random (+); int i;i=rand.nextint (100);

Initialization 25 does not have a direct effect (note: It does not work), Rand.nextint (100), 100 is the upper limit of the random number, the resulting random number is a 0-100 integer, excluding 100.

Use the following example:

Package Io;import Java.util.arraylist;import Java.util.random;public class Testrandom {public static void main (STR        Ing[] (args) {//Case 2//For the same random object as the seed, the generated sequence is the same.        Random ran1 = new random (10);        SYSTEM.OUT.PRINTLN ("Generates a sequence of random integers in [0,10] using a random object of seed 10:");        for (int i = 0; i < i++) {System.out.print (Ran1.nextint (10) + "");        } System.out.println ();        Random ran2 = new random (10);        SYSTEM.OUT.PRINTLN ("Generates a sequence of random integers in [0,10] using another random object of seed 10:");        for (int i = 0; i < i++) {System.out.print (Ran2.nextint (10) + "");          The/** * output is: * * generates a sequence of random integers in [0,10] using a random object of seed 10: * 3 0 3 0 6 6 7 8 1 4        * Generate a sequence of random integers in [0,10] using another random object with a seed of 10: * 3 0 3 0 6 6 7 8 1 4 * *///Case 3        The seed default for random objects generated without the parametric constructor is the number of milliseconds of the current system time.        Random r3 = new Random ();        System.out.println (); System.ouT.println ("Using the seed default is the number of milliseconds of the current system time to generate a random integer sequence in [0,10]");        for (int i = 0; i < i++) {System.out.print (R3.nextint (10) + "");          }/** * The output is: * * * * Use the seed default is the number of milliseconds of the current system time for random object generation [0,10] within a sequence of randomly ordered integers * 1 1 0 4 4 2 3 8 8 4 * *////In addition, the direct use of random does not prevent the generation of duplicate numbers, if you need to generate a sequence of random numbers that do not repeat, you need the help of arrays and collection classes ArrayList list=new Te        Strandom (). GETDIFFNO (10);        System.out.println ();    System.out.println ("produces n different random numbers:" +list);        }/** * generates n different random numbers with a random number interval of [0,10] * @param n * @return */public ArrayList getdiffno (int n) {        Generate [0-n] a non-repeating random number//list to hold these random numbers ArrayList list = new ArrayList ();        Random rand = new Random ();        boolean[] bool = new Boolean[n];        int num = 0;            for (int i = 0; i < n; i++) {do {//If the resulting number is the same as the continuation loop num = Rand.nextint (n);            } while (Bool[num]);     Bool[num] = true;       List.add (num);    } return list; }        }

Note: The following is a summary of the Java.util.Random () method:

    1. protected int Next (int bits): Generates the next pseudo-random number.
    2. Boolean Nextboolean (): Returns the next pseudo-random number, which is a Boolean value derived from the uniform distribution of this random number generator sequence.
    3. void Nextbytes (byte[] bytes): Generates a random byte and places it in a user-supplied byte array.
    4. Double nextdouble (): Returns the next pseudo-random number, which is a double value that is evenly distributed between 0.0 and 1.0, taken from this random number generator sequence.
    5. Float nextfloat (): Returns the next pseudo-random number, which is taken from this random number generator sequence and evenly distributes the float value between 0.0 and 1.0.
    6. Double Nextgaussian (): Returns the next pseudo-random number, which is a double value of Gaussian ("normal") distribution taken from this random number generator sequence, with an average of 0.0 standard deviations of 1.0.
    7. int Nextint (): Returns the next pseudo-random number, which is an int value that is evenly distributed in the sequence of this random number generator.
    8. int nextint (int n): Returns a pseudo-random number, which is an int value that is taken from the sequence of this random number generator and is evenly distributed between (including and specified values (not included).
    9. Long Nextlong (): Returns the next pseudo-random number, which is a long value derived from the uniform distribution of this random number generator sequence.
    10. void Setseed (Long Seed): Sets the seed of this random number generator with a single long seed.

Here are a few examples:

    1. The fractional number that generates the [0,1.0] interval: double D1 = r.nextdouble ();
    2. decimal for generating [0,5.0] interval: Double d2 = r.nextdouble () * 5;
    3. Generate decimal for [1,2.5] interval: Double d3 = r.nextdouble () * 1.5 + 1;
    4. Generates an integer from 231 to 231-1: int n = r.nextint ();
    5. Integer that generates the [0,10] interval:

int n2 = R.nextint (10);//Method One

N2 = Math.Abs (r.nextint ()% 10);//Method Two

The random () function in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.