Package cn.wangbingan.vip;import java.util.random;/** * math.random () and random.nextint () differences * * @author ak * */public class randomtest {public static void main (String[] args) {// TODO Auto-generated method stub// Random Number Object Random random = new random ();// start time long starttime1 = system.nanotime ();// generate random number Long a = random.nextint (10000);// end time long Endtime1 = system.nanotime ();// time consuming long time1 = endtime1 - starttime1 ; System.out.println ("Generate random Number:" + a + "=>random Time:" + time1);// start time long starttime2 = system.nanotime ();// generate random number int b = (int) (Math.random () * 10000);// End Time Long endtime2 = system.nanotime ();// time consuming long time2 = endtime2 - starttime2; System.out.println ("Generate random Number:" + b + "=>math Time:" + time2);}}
Output Result:
Generate random Number: 9441=>random time: 11000
Generate random Number: 7109=>math time: 43000
The former generates a random number that is more efficient than the latter, which is about 50% to 80% of the time, possibly higher.
This is caused by the following reasons:
Math.random () is an internal method of random.nextdouble (). (So I'm sure Dad's more efficient than his son.)
Random.nextdouble () uses Random.next () two times, with a uniform distribution range of 0 to 1-(2 ^-53).
Random.nextint (n) uses Random.next () no more than two times, and returns a distribution with a range of 0 to N-1
Math.random () and random.nextint () differences