Math.random () and random.nextint () differences

Source: Internet
Author: User

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

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.