3 ways to get random numbers from Java _java

Source: Internet
Author: User
Tags abs generator time in milliseconds stringbuffer

This paper mainly introduces 3 kinds of methods of obtaining random number in Java, mainly using random () function to realize

Method 1

(data type) (Minimum +math.random () * (maximum-min +1)) Example:

(int) (1+math.random () * (10-1+1))

from 1 to 10 int type with number

Method 2

Get random numbers

for (int i=0;i<30;i++)
{System.out.println ((int) (1+math.random () *10));}
(int) (1+math.random () *10)

Through Java. The random method of the math package gets 1-10 of the int random number

The formula is: a random number with a minimum value---maximum (integer)

(type) Minimum value +math.random () * Maximum value

Method 3

Random ra =new Random ();
for (int i=0;i<30;i++)
{System.out.println (Ra.nextint (10) +1);}

By using the Nextint method of the random class in the Java.util package, we get the 1-10 int random number

Generate any random decimal number from 0 to 1:

To generate a random decimal number for a [0,d) interval, and D is any positive decimal, you only need to multiply the return value of the Nextdouble method by D.

[N1,N2]

i.e. ra.nextdouble () * (N2-N1) +n1

Several ways to generate random numbers in Java

In J2SE we can use the Math.random () method to produce a random number, the random number is a double between 0-1, we can multiply him by a certain number, such as times 100, he is a random within 100, this is not in J2ME.

Two. In Java.util this package provides a random class, we can create a new random object to produce random numbers, he can produce random integers, random float, random double, random long, This is also a method that we often use in J2ME programs to take random numbers.

Three. In our system class there is a Currenttimemillis () method that returns a number of milliseconds from January 1, 1970 0:0 0 seconds to the present, and the return type is long, we can take him as a random number, we can take him to some number modulo, We can limit him to one area.

In fact, the default construction method of random is to use the third method above to produce random numbers.

For the random class in method two, the following are described:

There are two ways to build a java.util.Random class: with seeds and without seeds

Without seed:

This way will return a random number, and the results of each run are different

public class Randomtest {public
static void Main (string[] args) {
java.util.Random r=new java.util.Random (); 
   for (int i=0;i<10;i++) {
  System.out.println (R.nextint ());
}
}

With seeds:

This way, no matter how many times the program runs, the return result is the same

public static void Main (string[] args) {
java.util.Random r=new java.util.Random (a);
for (int i=0;i<10;i++) {
  System.out.println (R.nextint ());
}
}

The difference between the two ways is

(1) First Please open Java Doc, we will see the description of the random class:

An instance of this class is used to generate a pseudo random number stream, which uses a 48-bit seed that can be modified using a linear congruence formula.

If two Random instances are created with the same seed, the same method call sequence is made for each instance, which generates and returns the same number sequence. To ensure this, we specify a specific algorithm for class random. For the full portability of Java code, the Java implementation must let class Random use all of the algorithms shown here. However, subclasses of the Random class are allowed to use other algorithms as long as they conform to the general contract of all methods.

Java Doc has explained the random class very well, and our tests have validated this.

(2) If no seed number is provided, the number of seeds for the random instance will be the number of milliseconds in the current time, and the number of milliseconds for the current time can be obtained by System.currenttimemillis (). To open the source code for the JDK, we can see this very clearly.

Public Random () {This (System.currenttimemillis ());}

Other than that:

Description of the Nextint (), nextint (int n) method of the Random object:

int Nextint ()//Returns the next pseudo-random number, which is a uniformly distributed int value in the sequence of this random number generator.

int nextint (int n)//Returns a pseudo random number, which is an int value that is taken out of the sequence of the random number generator, evenly distributed between 0 (including) and the specified value (excluding).

Java Random Number Summary

Random numbers are widely used in practice, such as to generate a fixed-length string and number. Or it generates an indefinite number of digits, or a random selection of simulations, and so on. Java provides the most basic tool that can help developers to achieve this.

How to generate Java random numbers

In Java, the concept of random numbers in general, there are three kinds.

1, through System.currenttimemillis () to obtain a current time of the number of milliseconds long number.

2. Returns a double value from 0 to 1 by Math.random ().

3, through the random class to produce a random number, this is a professional random tool class, powerful.

Second, Random class API description

1, Java API description

An instance of the random class is used to generate a pseudo random number stream. This class uses 48-bit seeds and modifies them using a linear congruence formula (see Donald Knuth, "The Art of Computer programming, Volume 2", sect. 3.2.1).

If two Random instances are created with the same seed, the same method call sequence is made for each instance, which generates and returns the same number sequence. In order to guarantee the implementation of the property, a specific algorithm is specified for the class Random.

Many applications will find the random method in the Math class easier to use.

2. Summary of methods

Random ()//Create a new random number generator.

Random (long Seed)//use a single long seed to create a new random number generator: public Random (Long Seed) {setseed (seed); The next method uses it to hold the state of the random number generator.

protected int Next (int bits): Generates the next pseudo random number.

Boolean Nextboolean (): Returns the next pseudo-random number, which is a uniformly distributed Boolean value taken out of the sequence of the random number generator.

void Nextbytes (byte[] bytes): Generates random bytes and places them in a user-supplied byte array.

Double nextdouble (): Returns the next pseudo-random number, which is the evenly spaced double of 0.0 and 1.0 removed from the sequence of random number generators.

Float nextfloat (): Returns the next pseudo-random number, which is a float value that is evenly distributed between 0.0 and 1.0 from the sequence of random number generators.

Double Nextgaussian (): Returns the next pseudo-random number, which is a double value of Gaussian ("normal") distribution in the sequence of this random number generator, with an average of 0.0 and a standard deviation of 1.0.

int Nextint (): Returns the next pseudo-random number, which is a uniformly distributed int value in the sequence of this random number generator.

int nextint (int n): Returns a pseudo-random number, which is an int value that is removed from the sequence of the random number generator, evenly distributed between 0 (including) and the specified value (not included).

Long Nextlong (): Returns the next pseudo-random number, which is a uniformly distributed long value from the sequence of the random number generator.

void Setseed (Long Seed): Sets the seed of this random number generator with a single long seed.

Three, random class use explanation

1, the difference between the seed and the random class is the use of the strategy of the seed and random with no seeds.

Popular said that the difference between the two is: with seeds, each run generated results are the same.

Without seeds, each run generated is random, there is no law to say.

2. Create random objects without seeds
  

Random Random = new Random ();

3, there are two ways to create random objects without seeds:

1) Random Random = new Random (555L);

2) Random Random = new Random (); Random.setseed (555L);

Four, test

Using an example to illustrate the use of the above
  

Import Java.util.Random;
  public class Testrandomnum {public static void main (string[] args) {randomtest ();
  Testnoseed ();
  TestSeed1 ();
  TestSeed2 ();
  public static void Randomtest () {System.out.println ("--------------test ()--------------");
  Returns the current time in milliseconds.
  Long R1 = System.currenttimemillis ();
  Returns a double with a plus sign that is greater than or equal to 0.0, less than 1.0.
  Double r2 = math.random ();
  The Random class is used to get the next random integer int r3 = new Random (). Nextint ();
  System.out.println ("r1 =" + r1);
  SYSTEM.OUT.PRINTLN ("r3 =" + R2);
  SYSTEM.OUT.PRINTLN ("r2 =" + R3);
  public static void Testnoseed () {System.out.println ("--------------testnoseed ()--------------");
  Create a test Random object with no seed Random Random = new Random ();
  for (int i = 0; i < 3; i++) {System.out.println (Random.nextint ());
  The public static void TestSeed1 () {System.out.println ("--------------testSeed1 ()--------------");
  Create a test Random object with seeds Random Random = new Random (555L); for (int i = 0; i < 3; i++) {SystEm.out.println (Random.nextint ());
  The public static void TestSeed2 () {System.out.println ("--------------testSeed2 ()--------------");
  Create a test Random object with seeds Random Random = new Random ();
  Random.setseed (555L);
  for (int i = 0; i < 3; i++) {System.out.println (Random.nextint ());
 }   }   }

Run Result:

--------------Test ()--------------
R1 = 1227108626582
R3 = 0.5324887850155043
r2 =-368083737
--------------testnoseed ()--------------
809503475
1585541532
-645134204
--------------testSeed1 ()--------------
-1367481220
292886146
-1462441651
--------------TestSeed2 ()--------------
-1367481220
292886146
-1462441651
Process finished with exit code 0

With the results of the testSeed1 () and TestSeed2 () methods, we can see that the two print results are the same, because they are the same seed, run again, the result is the same, this is the characteristic with the seed random number. Without seeds, the results of each run are random.

V. Comprehensive application

Here's how to show the usage by using a recently written random number tool class:
 

 Import Java.util.Random; public class Randomutils {public static final String Allchar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS
  TUVWXYZ ";
  public static final String Letterchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
  
  public static final String Numberchar = "0123456789";
  public static String generatestring (int length) {stringbuffer sb = new StringBuffer ();
  Random Random = new Random ();
  for (int i = 0; i < length; i++) {Sb.append (Allchar.charat (Random.nextint (Allchar.length ()));
  return sb.tostring ();
  public static String generatemixstring (int length) {stringbuffer sb = new StringBuffer ();
  Random Random = new Random ();
  for (int i = 0; i < length; i++) {Sb.append (Allchar.charat (Random.nextint (Letterchar.length ()));
  return sb.tostring ();
  public static String generatelowerstring (int. length) {return generatemixstring (length). toLowerCase (); } public static String Generateupperstring (int length) {return generatemixstring (length). toUpperCase ();
  public static String generatezerostring (int length) {stringbuffer sb = new StringBuffer ();
  for (int i = 0; i < length; i++) {sb.append (' 0 ');
  return sb.tostring ();
  public static String tofixdlengthstring (long num, int fixdlenth) {StringBuffer sb = new StringBuffer ();
  String strnum = string.valueof (num);
  if (fixdlenth-strnum.length () >= 0) {sb.append (generatezerostring (Fixdlenth-strnum.length ()));
  else {throw new RuntimeException ("Converts the number + num +" to a string that has a length of "+ Fixdlenth +" is abnormal! ");
  } sb.append (Strnum);
  return sb.tostring ();
  public static String tofixdlengthstring (int num, int fixdlenth) {StringBuffer sb = new StringBuffer ();
  String strnum = string.valueof (num);
  if (fixdlenth-strnum.length () >= 0) {sb.append (generatezerostring (Fixdlenth-strnum.length ())); else {throw new RuntimeException ("Convert number + num +" to length = + Fixdlenth +) "The string has an exception!");
  } sb.append (Strnum);
  return sb.tostring ();
  public static void Main (string[] args) {System.out.println (generatestring (15));
  System.out.println (generatemixstring (15));
  System.out.println (generatelowerstring (15));
  System.out.println (generateupperstring (15));
  System.out.println (generatezerostring (15));
  System.out.println (tofixdlengthstring (123, 15));
  System.out.println (Tofixdlengthstring (123L, 15));
 }   }

Run Result:

Vwmbpinbzfgcphg
23hyraHdJkKPwMv
Tigowetbwkm1nde
bpz1knejphb115n
000000000000000
000000000000123
000000000000123
Process finished with exit code 0

Vi. Summary 

1, random number is very commonly used in Java, there are three ways to produce, to random random number of the most complex use.

2, the random class object has whether to carry the seed the cent, with the seed as long as the seed is same, many times runs, produces the random number the result always is like that.

3. There are two kinds of seed objects with seed random numbers, the effect is the same. But the random number with seeds seems to be of little use.

4, random function covers the function of Math.random ().

5. Random numbers can be used to achieve complex random data such as random strings.

6, do not study the random number does not duplicate, the significance is not big.

In Java we can use the Java.util.Random class to produce a random number generator. It has two forms of constructors, namely random () and random (long Seed). Random () uses the current time, System.currenttimemillis () as the seed of the generator, and Random (long Seed) uses the specified seed as the seed of the generator.

After the random number generator (Random) object is produced, different types of random numbers are obtained by calling different Method:nextint (), Nextlong (), Nextfloat () and nextdouble ().

1> Generating Random numbers

  Random Random = new Random ();
      Random Random = new Random (100);//Specify seed number 100

Random calls different methods to get random numbers.

If 2 random objects use the same seed (for example, all 100) and call the same function in the same order, they return exactly the same value. The output of two random objects is exactly the same as in the following code

  Import java.util.*;
     Class Testrandom {public
        static void Main (string[] args) {
           Random random1 = new Random (MB);
           System.out.println (Random1.nextint ());
           System.out.println (Random1.nextfloat ());
           System.out.println (Random1.nextboolean ());
           Random random2 = new Random (MB);
           System.out.println (Random2.nextint ());
           System.out.println (Random2.nextfloat ());
           System.out.println (Random2.nextboolean ());
        }
      

2> a random number within a specified range

Random number control in a range, using modulo operator%

 Import java.util.*;
         Class Testrandom {public
           static void Main (string[] args) {
              Random Random = new Random ();
              for (int i = 0; i < 10;i++) {
                System.out.println (Math.Abs (Random.nextint ()));}}
         

The obtained random number has positive negative, using Math.Abs to get the data range to be non-negative

3> gets the number of distinct random numbers within a specified range

 Import java.util.*;
      Class Testrandom {public
         static void Main (string[] args) {
            int[] intret = new Int[6];
            int INTRD = 0; Hold random number
            int count = 0;//record number of random numbers generated
            int flag = 0;//whether the flag while
            (count<6) {
              Random RDM = new Random (S) has been generated Ystem.currenttimemillis ());
              INTRD = Math.Abs (Rdm.nextint ()) 2+1;
              for (int i=0;i<count;i++) {
                if (INTRET[I]==INTRD) {
                  flag = 1;
                  break;
                else{
                  flag = 0;
                }
              }
              if (flag==0) {
                Intret[count] = INTRD;
                count++
              }
          }
         for (int t=0;t<6;t++) {
           System.out.println (t+ "->" +intret[t]);}}
      

Can random numbers in Java be repeated? Can the random numbers generated in Java be used to generate database primary keys? With this problem, we did a series of tests.

1. Test one: Use the random () constructor with no parameters

public class Randomtest {public

static void Main (string[] args) {
   java.util.Random r=new java.util.Random (); 
   for (int i=0;i<10;i++) {
     System.out.println (R.nextint ());}}}


Program Run Result:

-1761145445
-1070533012
216216989
-910884656
-1408725314
-1091802870
1681403823
-1099867456
347034376
-1277853157

Run the program again:

-169416241
220377062
-1140589550
-1364404766
-1088116756
2134626361
-546049728
1132916742
-1522319721
1787867608

From the above test, we can see that the random numbers produced by using the random () constructor with no parameters do not repeat. So, under what circumstances would Java produce duplicate random numbers? And look at the test below.

2. Test two: Set seed number for random

public class Randomtest_repeat {public
  
  static void Main (string[] args) {
    java.util.Random r=new Java.util.Random (ten);
    for (int i=0;i<10;i++) {
      System.out.println (R.nextint ());
    }
  }
}

No matter how many times the program runs, the result is always:

-1157793070
1913984760
1107254586
1773446580
254270492
-1408064384
1048475594
1581279777
-778209333
1532292428

Even on different machines, the test results will not change!

3. Causal Analysis:

(1) First Please open Java Doc, we will see the description of the random class:

An instance of this class is used to generate a pseudo-random stream, which uses a 48-bit seed that can be modified using a linear congruence formula (see Donald Knuth's Art of Computer programming, Volume 2, sect. 3.2.1).

If two Random instances are created with the same seed, the same method call sequence is made for each instance, which generates and returns the same number sequence. To ensure this, we specify a specific algorithm for class random. For the full portability of Java code, the Java implementation must let class Random use all of the algorithms shown here. However, subclasses of the Random class are allowed to use other algorithms as long as they conform to the general contract of all methods.

Java Doc has explained the random class very well, and our tests have validated this.

(2) If no seed number is provided, the number of seeds for the random instance will be the number of milliseconds in the current time, and the number of milliseconds for the current time can be obtained by System.currenttimemillis (). To open the source code for the JDK, we can see this very clearly.

Public Random () {This (System.currenttimemillis ());}

4. Conclusion:

Through the above test and analysis, we will have a more profound understanding of the random class. At the same time, I think, by reading the Java Doc's API documentation, you can improve our Java programming capabilities, to "know it"; Once you encounter a puzzling problem, you might as well open Java source code, so we can do "know why".

There are generally two kinds of random numbers in Java, one is the random () method in math, and the other is the random class.

One, Math.random ()

The decimal number of the 0<x<1 is generated.

Example: How to write, generate randomly generated one of the number of 0~100?

Math.random () returns just a decimal number from 0 to 1, and if you want 50 to 100, zoom in 50 times, or 0 to 50, or decimal, or, if you want an integer, cast an int, then add 50 to 50~100.

Final code: (int) (Math.random () *50) + 50

Second, Random class

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

At random, the origin number of the random algorithm is called seed number, and a certain transformation is made on the basis of the seed number, which produces the random number needed.
The random object of the same seed number, the same number of random numbers generated are exactly the same. That is, two random objects with the same seed count, the first generation of random numbers are exactly the same, and the second generation of random numbers is exactly the same.

2. Common methods in random class

The methods in the Random class are simple, and the functionality of each method is easy to understand. It should be explained that the random numbers generated by each method in the random class are evenly distributed, which means that the probability of the generation of the numbers within the interval is equal. Here's a basic introduction to these methods:

A, public boolean nextboolean ()

The effect of this method is to generate a random Boolean value that yields true and false values equal to the probability of 50%.

B, public double nextdouble ()

The effect of this method is to generate a random double value that is between [0,1.0], where the brackets represent the inclusion of the interval endpoint, and the parentheses represent a random decimal number between 0 and 1 that contains no interval endpoint, containing 0 without 1.0.

c, public int nextint ()

The effect of this method is to generate a random int value that is in the range of int, that is, 2 of 31 times to 2 of 31 times to 1.

If you need to generate an int value for a specified interval, you need to make some mathematical transformations, depending on the code in the following example.

d, public int nextint (int n)

The effect of this method is to generate a random int value that is in the range of [0,n], that is, a random int value between 0 and N, containing 0 without n.

If you want to generate an int value for a specified interval, you also need to make some mathematical transformations, depending on the code in the following example.

E, public void setseed (long Seed)

The purpose of this method is to reset the number of seeds in the random object. After the seed count is set, the random object and the same seed number are created with the same random object as the New keyword.

3, Random class use example

Using the random class, which typically generates random numbers for a specified interval, the following describes how to generate random numbers of corresponding intervals. The following code for generating random numbers is generated using the following random object R:

Random r = new Random ();

A, the decimal number of the generation [0,1.0] Interval

Double D1 = r.nextdouble ();

Directly using the Nextdouble method to obtain.

b, the decimal number of the generation [0,5.0] Interval

Double D2 = r.nextdouble () * 5;

Because the Nextdouble method generates a numerical interval of [0,1.0], extending the interval by 5 times times is the required interval.

Similarly, to generate a random decimal number in a [0,d) interval, d is any positive decimal, you only need to multiply the return value of the Nextdouble method by D.

C, Generation [1,2.5] interval decimal [N1,N2]

Double d3 = r.nextdouble () * 1.5 + 1; "That is, r.nextdouble () * (N2-N1) +n1"

To generate a random decimal number in the [1,2.5] interval, you only need to generate the random numbers of the [0,1.5] interval first, and then add a random number interval of 1.

Similarly, to generate random numbers (where D1 is not equal to 0) of any range of decimal intervals [D1,D2] that do not start from 0, you only need to generate a random number of [0,d2-d1] intervals, and then add D1 to the generated random number interval.

d, generate any integer

int n1 = R.nextint ();

Use the Nextint method directly.

E, integers that generate [0,10] intervals

int n2 = R.nextint (a);
N2 = Math.Abs (r.nextint ()% 10);

Both lines of code can generate integers in the [0,10] interval.

The first implementation is implemented directly using the nextint (int n) method in the Random class.

In the second implementation, first call the Nextint () method to generate an arbitrary int number, this number and 10 after the generation of the numerical interval is ( -10,10), because according to the mathematical rules of the absolute value of the remainder is less than the divisor, and then the interval for the absolute values, the resulting interval is [0,10).

Similarly, random integers that generate arbitrary [0,n] intervals can use the following code:

int n2 = R.nextint (n);
N2 = Math.Abs (r.nextint ()% n);

F, integers that generate [0,10] intervals

int n3 = R.nextint (one);
N3 = Math.Abs (R.nextint ()% 11);

Relative to the integer interval, [0,10] intervals and [0,11] intervals are equivalent, so the integers of the [0,11) interval are generated.

g, integers that generate [ -3,15] intervals

int N4 = R.nextint (3);  "That is, R.nextint () * (N2-N1) +n1" N1 is a negative number
N4 = Math.Abs (R.nextint ()% 18)-3;  

To generate a random integer that is not from the 0 start interval, you can see a description of the implementation principle of the decimal interval, which is not starting from 0.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.