How Java random numbers are generated

Source: Internet
Author: User
Tags constructor current time final generator integer printf range

This chapter first explains several ways to generate Java random numbers, and then demonstrates them through an example.

Broadly speaking, there are three ways to generate random numbers in Java: (01). The System.currenttimemillis () is used to get a long number of milliseconds for the current time. (02). Returns a double value from 0 to 1 by Math.random (). (03). By random class to produce a random number, this is a professional random tool class, powerful.

1th Kind

The random number is obtained by System.currenttimemillis (). is actually getting the current number of milliseconds, which is a long type. Use the following methods:

Finallong L = System.currenttimemillis ();

To get an integer of type int, you only need to change the result above to an int type. For example, get an int integer between [0, 100). The method is as follows:

Finallong L = System.currenttimemillis (); Finalint i = (int) (l% 100);

2nd Kind

The random number is obtained by Math.random (). In effect, it returns a double value of 0 (contained) to 1 (not included). Use the following methods:

Finaldouble d = math.random ();

To get an integer of type int, you only need to change the result above to an int type. For example, get an int integer between [0, 100). The method is as follows:

Finaldouble d = math.random (); Finalint i = (int) (D*100);

3rd Kind

The random class is used to get the random number.

Use the following method: (01) Create the Random object. There are two ways to create a random object, as follows:

Random Random = new Random ();//default construction method
Random Random = new Random (1000);//Specify seed number

(02) Obtaining random numbers by random objects. The random value types supported by Random include: Boolean, Byte, int, long, float, double. For example, get an int integer between [0, 100). The method is as follows:

int i2 = random.nextint (100);

function interface of Random

Constructor (a): Creates a new random number builder. 
Random () 
//Constructor (ii): Creates a new random number generator with a single long seed: public Random (Long Seed) {setseed (seed); The next method uses it to hold the state of the random number generator.
Random (Long Seed) 
     
Boolean Nextboolean ()         //Returns the Next "Boolean" pseudo random number. 
void    nextbytes (byte[] buf)//generates random bytes and places them in a byte array buf. 
double  nextdouble ()          //Returns a random number with a double type between [0.0, 1.0). 
float   nextfloat ()           //Returns a random number of float type between "[0.0, 1.0)". 
int     nextint ()             //Returns the next "int type" random number. 
int     nextint (int n)        //Returns a random number of type int between "[0, N)". 
long    Nextlong ()            //Returns the next "long" random number. 
synchronized Double Nextgaussian ()   //Returns the next "double" random number, which is a double value of Gaussian ("normal") distribution with an average of 0.0 and a standard deviation of 1.0. 
synchronized void Setseed (long Seed)///use a single long seed to set the seed of this random number generator.

Get random Number sample

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

The following example shows the above 3 ways to get random numbers. The source code is as follows (Randomtest.java):

Import Java.util.Random;
     
Import Java.lang.Math; /** * Java random number test program.
 There are 3 ways to get random numbers: * (01), by System.currenttimemillis () to obtain a long number of the current time milliseconds.
 * (02), by Math.random () returns a double value from 0 to 1.
 * (03), through the random class to produce a random number, this is a professional random tool class, powerful. * * @author Skywang * @email kuiwu-wang@163.com/public class randomtest{public static void main (String ar
     
        Gs[]) {//Returns a random number Testsystemtimemillis () through the system's Currenttimemillis ();
     
        The random number Testmathrandom () is returned by the random () of the math.
        Create a new "seed 1000" Random object and pass the seed to test the Random API Testrandomapis (new Random (1000), "1st Random (1000)");
        Testrandomapis (New Random (1000), "2nd Random (1000)");
        Create a new Random object for the default seed and pass the seed to test the Random API Testrandomapis (New Random (), "1st Random ()");
    Testrandomapis (New Random (), "2nd Random ()");
        /** * Returns a random number-01: Test system Currenttimemillis ()/private static void Testsystemtimemillis () {
 Pass       Final long L = System.currenttimemillis ();
     
        The integer final int i = (int) (l% 100) is obtained through L (0, 100);
    System.out.printf ("\ n----system.currenttimemillis ()----\ n l=%s i=%s\n", l, I); /** * Returns random number-02: Test math's random ()/private static void Testmathrandom () {//via Math
        The random () function returns a double type random number, the range [0.0, 1.0) Final Double d = math.random ();
     
        The integer final int i = (int) (D*100) is obtained by D to get a [0, 100];
    System.out.printf ("\ n----math.random ()----\ n d=%s i=%s\n", D, I); /** * Returns random number-03: Test Random API/private static void Testrandomapis (Random Random, String ti
     
        TLE) {Final int buffer_len = 5;
        Gets a random Boolean value of Boolean B = Random.nextboolean ();
        Get the random array buf[] byte[] buf = new Byte[buffer_len];
        Random.nextbytes (BUF);
        Gets a random double value, range [0.0, 1.0) Double d = random.nextdouble (); BeenTake the random float value, the range [0.0, 1.0) Float F = random.nextfloat ();
        Gets the random int value int i1 = Random.nextint ();
        Gets the int value int i2 = random.nextint (100) between the random [0,100];
        Gets the random Gaussian distribution of double double g = Random.nextgaussian ();
     
        Gets a random long value of long L = Random.nextlong ();  System.out.printf ("\ n----%s----\nb=%s, d=%s, f=%s, i1=%s, i2=%s, g=%s, l=%s, buf=[", title, B, D, F, I1,
        I2, G, L);
        for (byte bt:buf) System.out.printf ("%s,", BT);
    System.out.println ("]"); }
}
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.