Java中Random.nextInt(100)和Math.random()*100的区别

Random.nextInt()是java.util.Random类中的方法。

其源码:

    public int nextInt(int bound) {
        if (bound <= 0)
            throw new IllegalArgumentException(BadBound);

        int r = next(31);
        int m = bound - 1;
        if ((bound & m) == 0)  // i.e., bound is a power of 2
            r = (int)((bound * (long)r) >> 31);
        else {
            for (int u = r;
                 u - (r = u % bound) + m < 0;
                 u = next(31))
                ;
        }
        return r;
    }

其返回随机值在0-(n-1)区间内分布。

Math.random()是math工具类中的产生随机数的方法。

其源码:

    public static double random() {
        return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
    }
    private static final class RandomNumberGeneratorHolder {
        static final Random randomNumberGenerator = new Random();
    }

 

    public double nextDouble() {
        return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
    }

源码可知是Math.random调用Random的nextDouble方法。其返回值范围是0-(21-(2^-53)

效率上:测试代码

public static void main(String[] args){
        Test test = new Test();
        System.out.println("Math.random()一百万次时间:"+test.random1()+"ms");
        System.out.println("random.nextInt一百万次时间:"+test.random2()+"ms");
    }
     int random1(){
         long start = System.currentTimeMillis();
         System.out.println("start"+System.currentTimeMillis());
        for (int i = 0;i<1000000;i++) {
            int ran = (int)(Math.random()*1000);
        }
         long end = System.currentTimeMillis();
         System.out.println("end"+System.currentTimeMillis());
        return (int) (end-start);
    }
    int random2(){
        Random random = new Random();
        long start = System.currentTimeMillis();
        System.out.println("start"+System.currentTimeMillis());
        for (int i = 0;i<1000000;i++) {
            int ran = (int)(random.nextInt(1000));
        }
        long end = System.currentTimeMillis();
        System.out.println("end"+System.currentTimeMillis());
        return (int) (end-start);
    }

结果:

start1561973201713
end1561973201768
Math.random()一百万次时间:54ms
start1561973201768
end1561973201796
random.nextInt一百万次时间:28ms

效率上使用Random.nextInt()会比Math.random快,使用时间只占后者50%到80%的时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值