码迷,mamicode.com
首页 > 其他好文 > 详细

Math.random()和Random.nextInt()区别

时间:2015-09-16 13:00:14      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

package cn.wangbingan.vip;

import java.util.Random;

/**
 * Math.random()和Random.nextInt()区别
 * 
 * @author AK
 * 
 */
public class RandomTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 随机数对象
		Random random = new Random();
		// 开始时间
		long startTime1 = System.nanoTime();
		// 生成随机数
		long a = random.nextInt(10000);
		// 结束时间
		long endTime1 = System.nanoTime();
		// 耗时时间
		long time1 = endTime1 - startTime1;
		System.out.println("生成随机数:" + a + "=>Random耗时:" + time1);

		// 开始时间
		long startTime2 = System.nanoTime();
		// 生成随机数
		int b = (int) (Math.random() * 10000);
		// 结束时间
		long endTime2 = System.nanoTime();
		// 耗时时间
		long time2 = endTime2 - startTime2;
		System.out.println("生成随机数:" + b + "=>Math耗时:" + time2);

	}

}

输出结果:

生成随机数:9441=>Random耗时:11000

生成随机数:7109=>Math耗时:43000

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

造成这个原因如下:

Math.random()是Random.nextDouble()的一个内部方法.(所以肯定爸爸的效率高于儿子了)

Random.nextDouble()使用Random.next()两次,均匀的分布范围为0到1 - (2 ^ -53).

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


Math.random()和Random.nextInt()区别

标签:

原文地址:http://my.oschina.net/Tsher2015/blog/506708

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!