在项目中使用哪个随机数

文章参考 http://liukai.iteye.com/blog/433718

今天用了find bugs后查出来了个问题 
Google了下 
发现 
Random.nextint() 和Math.random()的区别 

(经下面朋友提醒,再去Google了下 终于知道两者的区别了~,E文不好真知道大体意思) 
http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint 
2个Exp: 

Random rand = new Random();  
        long startTime = System.nanoTime() ;  
        int i1 = rand.nextInt(1000000000);  
        System.out.println(i1);  
        long endTime = System.nanoTime();  
        System.out.println("Random.nextInt(): " + (endTime - startTime));  
  
        long startTime2 = System.nanoTime();  
        int i2 = (int) (java.lang.Math.random() * 1000000000);  
        System.out.println(i2);  
        long endTime2 = System.nanoTime();  
        System.out.println("Math.random():" + (endTime2 - startTime2));  

 


前者生成的随机数效率高于后者,时间上前者大约是后者50%到80%的时间. 

造成这个原因如下: 
Math.random()是Random.nextDouble()的一个内部方法. 
Random.nextDouble()使用Random.next()两次,均匀的分布范围为0到1 - (2 ^ -53). 


Random.nextInt(n)的使用Random.next()不多于两次, 返回值范围为0到n - 1的分布 

相关文章:

  • 2022-12-23
  • 2022-02-10
  • 2021-12-24
  • 2021-05-24
  • 2021-11-30
  • 2021-12-30
猜你喜欢
  • 2021-06-15
  • 2021-09-17
  • 2021-09-17
  • 2021-12-03
  • 2021-07-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案