java中(int)(math.random()是什么意思_java – Math.random()和Random.nextInt(int)

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn’t alter the number of possible values, and casting to an int then forces these values into one of six ‘buckets’ (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,有两种不同的方式可以生成随机数:使用Math类的random()方法和使用java.util.Random类。 1. Math类的random()方法: Math类是Java内置的数学类,其有一个静态方法random(),用于生成一个0到1之间的随机浮点数。具体使用方法如下: ```java double randomNum = Math.random(); // 生成一个0到1之间的随机浮点数 ``` 这个方法会返回一个大于等于0且小于1的伪随机浮点数。如果你需要生成其他范围的随机数,可以使用乘法和加法进行缩放和偏移。例如,如果你想生成一个0到100之间的随机整数,可以使用以下代码: ```java int randomInt = (int) (Math.random() * 101); // 生成一个0到100之间的随机整数 ``` 注意:使用Math类的random()方法生成的随机数是伪随机数,每次程序运行时都会生成相同的随机数序列。如果需要更高质量的随机数,可以考虑使用Random类。 2. Random类: Random类是Java提供的随机数生成器类,位于java.util包。使用Random类可以生成各种类型的随机数,包括整数、浮点数、布尔值等。以下是一个使用Random类生成随机整数的示例: ```java import java.util.Random; // 创建Random对象 Random random = new Random(); // 生成一个0到100之间的随机整数 int randomInt = random.nextInt(101); // 打印随机整数 System.out.println(randomInt); ``` Random类的nextInt()方法用于生成一个指定范围内的随机整数。在上述示例,nextInt(101)会生成一个0到100之间的随机整数。 总结:Math类的random()方法适用于简单的随机数生成需求,而Random类适用于更复杂的随机数生成需求,可以生成不同类型的随机数,并且具有更好的随机性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值