简体   繁体   English

Scala随机数生成器不在范围之间产生唯一的随机数

[英]Scala Random Number Generator Not Producing Unique Random Numbers Between A Range

I have the following code to generate new random numbers 我有以下代码来生成新的随机数

val start = 1
val end = 50000000
val rnd = new scala.util.Random

for (i < 1 to 25000000){
  val rnum = start + rnd.nextInt((end - start) + 1)

...
}

But this is producing duplicate random numbers now and again. 但是,这一次又一次地产生重复的随机数。 Is this a bug or have I done something stupid? 这是错误还是我做了一些愚蠢的事情?

Don't worry, this is not a bug, and you have not done anything stupid. 不用担心,这不是错误,您也没有做任何愚蠢的事情。 However you have missed the fact that a sequence of random numbers can contain duplicates . 但是,您已经错过了一个事实,即随机数序列可以包含重复项

The reasons are explained in the comments. 注释中说明了原因。

The problem is that humans don't have a good instinctive understanding of random numbers. 问题在于人类对随机数没有很好的本能理解。 If you ask people to write a series of digits they are very unlikely to repeat a digit, even though this should happen 10% of the time. 如果您要求人们写一系列数字,即使出现这种情况的可能性为10%,他们也不大可能重复一个数字。 If you ask people to write down 5 random digits they are unlikely to use the same digit twice, even though this should happen 70% of the time. 如果您要求人们写下5个随机数字,那么即使70%的情况下,他们都不太可能两次使用相同的数字。

There is no bug. 没有错误。 It selects randomly so chances are there that same element would be picked. 它随机选择,因此有机会选择相同的元素。 I prefer using the shuffle function of List. 我更喜欢使用List的shuffle功能。

val list = (1 to 100).toList

scala.util.Random.shuffle(list).take(1)

But creating a list of big number won't be an effective solution. 但是创建大量列表将不是一个有效的解决方案。 You can use the following way to generate a random number. 您可以使用以下方式生成随机数。

val seed = new java.util.Date().hashCode
val rand = new scala.util.Random(seed)
val someNum = rand.nextInt

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

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