Summary of the generation of random numbers in Java programming _java

Source: Internet
Author: User
Tags generator

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). System.currenttimemillis () to get a long number of milliseconds of 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. The 1th kind uses System.currenttimemillis () to obtain the random number
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:

Final long 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:

Final long L = System.currenttimemillis ();
final int i = (int) (l% 100);

The 2nd kind uses math.random () to obtain the random number
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:

Final Double 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:

Final Double D = math.random ();
final int i = (int) (D*100);

The 3rd kind uses the random class to obtain the random number
the random class is used to get the random number.
Use the following methods:
(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

EG1:
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 args[]) {

    The random number Testsystemtimemillis () is returned by the Currenttimemillis () of the system.

    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 ()"); /** * return random number-01: Test system Currenttimemillis ()/private static void Testsystemtimemillis () {//via fin
    Al long L = system.currenttimemillis (); Through l get a [0, 100) of the integers between the final int i = (int) (l% 100);
  System.out.printf ("\ n----system.currenttimemillis ()----\ n l=%s i=%s\n", l, I); /** * Returns random number-02: Test math Random ()/private static void Testmathrandom () {//returns a double by the random () function of the math
    Type random number, 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); /** * return random number-03: Test Random API/private static void Testrandomapis (Random Random, String title) {Final I

    NT 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 ();
    Gets 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]; Get a random Gaussian distribution 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 ("]");

 }
}

EG2:

Problem: A random number of two digits between the generation ( -10,10) that retains the decimal point.
Workaround:
1.java random number generation function Random r=new Random (); Floating-point random number between r.nextfloat ()//Generation (0,1). Multiply the above random number by 10 to get the random number between the generated (0,10).
2. Generate a Boolean type of random number to control the number of positive and negative: R.nextboolean ();
3. The method of keeping the decimal digits two digits: Math.floor (n*100+0.5)/100; The number obtained is double.
The code is as follows:
  

Import java.util.*;
public class Createrandom {public
float numrandom () {
float num;
Random r=new Random ();
Float value = (float) (Math.floor (R.nextfloat () *1000+0.5)/100);
Boolean B = R.nextboolean ();
if (b) {
num = value;
}
else{
num=0-value;
return
num;
Public
static void Main (string[] args) {
createrandom cr = new Createrandom ();
float num = Cr.numrandom ();
System.out.print (num);
}
}

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.