Random.nextInt()替換Math.random()


在項目中使用哪個隨機數

文章參考 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的分布 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM