The random () function in Java

Source: Internet
Author: User
Tags rand

Transferred from: https://www.cnblogs.com/ningvsban/p/3590722.html

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:

 PackageIO;ImportJava.util.Random; Public classTestrandom { Public Static voidMain (string[] args) {//Case 1System.out.println ("math.random () =" + Math.random ());//The result is a double with a range of [0.0,1.0]        intnum = (int) (Math.random () * 3);//be careful not to write (int) math.random (), which results in 0 because the cast is performed firstSystem.out.println ("num=" +num); /*** 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:

 PackageIO;Importjava.util.ArrayList;ImportJava.util.Random; Public classTestrandom { Public Static voidMain (string[] args) {//Case 2//for random objects with the same seed, the generated sequence is the same. Random Ran1 =NewRandom (10); System.out.println ("Generates a sequence of random integers in [0,10] using a random object with seed 10:");  for(inti = 0; I < 10; i++) {System.out.print (Ran1.nextint (10) + "");        } System.out.println (); Random ran2=NewRandom (10); System.out.println ("Generates a sequence of random integers in [0,10] using another random object with a seed of 10:");  for(inti = 0; I < 10; 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 * Use another A random object with a seed of 10 generates a sequence of randomly integers in [0,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 =NewRandom ();        System.out.println (); System.out.println ("Use the seed default is the number of milliseconds of the current system time to generate random integers in [0,10] sequence");  for(inti = 0; I < 10; i++) {System.out.print (R3.nextint (10) + ""); }        /*** The output is: * * * * * Using 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 avoid generating duplicate numbers, and if you need to generate a sequence of random numbers that do not repeat, you need the help of arrays and collection classesArrayList list=NewTestrandom (). GETDIFFNO (10);        System.out.println (); System.out.println ("produces n different random numbers:" +list); }        /*** Generate n different random numbers with a random number interval of [0,10] *@paramN *@return     */     PublicArrayList Getdiffno (intN) {        //generate [0-n] non-repeating random numbers//list is used to hold these random numbers .ArrayList list =NewArrayList (); Random Rand=NewRandom (); Boolean[] bool =New Boolean[n]; intnum = 0;  for(inti = 0; I < n; i++) {             Do {                //if the resulting number is the same, continue the loopnum =rand.nextint (n); }  while(Bool[num]); Bool[num]=true;        List.add (num); }        returnlist; }        }

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

References :

Http://blog.sina.com.cn/s/blog_93dc666c0101h3gd.html

http://blog.csdn.net/wpjava/article/details/6004492

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.