zoukankan      html  css  js  c++  java
  • Random.nextint() 和Math.random()的区别

    Random.nextint() 和Math.random()的区别

    Java代码  收藏代码
    1.         Random rand = new Random();  
    2.         long startTime = System.nanoTime() ;  
    3.         int i1 = rand.nextInt(1000000000);  
    4.         System.out.println(i1);  
    5.         long endTime = System.nanoTime();  
    6.         System.out.println("Random.nextInt(): " + (endTime - startTime));  
    7.   
    8.         long startTime2 = System.nanoTime();  
    9.         int i2 = (int) (java.lang.Math.random() * 1000000000);  
    10.         System.out.println(i2);  
    11.         long endTime2 = System.nanoTime();  
    12.         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的分布

  • 相关阅读:
    Eclipse常见配置及常用插件
    杂记
    表单双引号问题
    兼容ie的jquery ajax文件上传
    Markdown 學習
    jstl c标签
    java 在接口里函数不能重载?
    【转】Eclipse里项目名有红叉,但是展开后里面又没有红叉叉
    Android性能优化之一:ViewStub
    Merge用法
  • 原文地址:https://www.cnblogs.com/langtianya/p/4086795.html
Copyright © 2011-2022 走看看