简体   繁体   English

Java Math.random()随机性如何?

[英]Java Math.random() How random is it?

I am working on a project that needs to generate two random numbers from a given range (both of them at the same time, one after another) and check if they are equal to each other - if they are, proceed executing other code; 我正在做一个项目,该项目需要在给定范围内生成两个随机数(它们同时,一个又一个),并检查它们是否相等-如果相等,则继续执行其他代码。 if they aren't - generate the numbers again. 如果不是,请重新生成数字。 Now my question is, if we have a range [0;10], and the first randomly generated number turned out to be 5, is the probability of the second number also being 5 as good as any other number? 现在我的问题是,如果我们有一个范围[0; 10],并且第一个随机生成的数字竟然是5,那么第二个数字也和其他任何一个数字一样好5的可能性是吗? Specifically, does Math.random() have any "defense" against generating same number if it is called twice consecutively? 具体来说,如果Math.random()被连续调用两次,是否对生成相同的数字有任何“防御”? or it "tries" to not generate the same number? 还是“尝试”不生成相同的数字?

Generating the same number in the range [0,10] twice in succession is a perfectly valid occurrence for any random number generator. 对于任何随机数生成器而言,连续两次生成[0,10]范围内的同一数字是完全有效的情况。 If it took any steps to prevent that it wouldn't be random. 如果采取了任何措施来防止这种情况发生,那将不是随机的。

On any invocation, the chances of any individual number being chosen should be 1:11, and each choice should be independent of previous choices, so the chances that in a pair the second number matches the first is 1 in 11. 在任何调用中,选择任何单个数字的机会应为1:11,并且每个选择均应独立于先前的选择,因此,一对第二个数字与第一个匹配的几率是11分之一。

As to how random Math.random() is, it's pseudo-random , meaning it uses an algorithm to generate a series of evenly distributed numbers starting with a "seed" value. 至于Math.random()随机性,它是伪随机的 ,这意味着它使用一种算法来生成一系列以“ seed”值开头的均匀分布的数字。 It's not suitable for cryptography but quite good for simulations and other non-cryptographic uses. 它不适用于密码学,但是非常适合模拟和其他非密码学用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM