简体   繁体   English

使用 Scala 生成随机序列

[英]Generating a random sequence using Scala

I need to get a random sequence of 100 values from 10^-10 to 10^10 and storing to an Array using Scala.我需要从 10^-10 到 10^10 获取 100 个值的随机序列,并使用 Scala 存储到Array中。 I tried following but it didn't work我试过跟随但没有用

Array(scala.math.pow(10,-10).doubleValue to scala.math.pow(10,10).intValue by scala.math.pow(10,5).toLong)

Can anyone help me to figure out how to do this correctly?谁能帮我弄清楚如何正确地做到这一点?

So you need to fill() the array with Random elements.所以你需要用Random元素fill()数组。

import scala.util.Random

val rndm = new Random(1911L)
Array.fill(100)(rndm.between(math.pow(10,-10), math.pow(10,10)))
//res0: Array[Double] = Array(6.08868427907728E9
// , 3.29548545155816E9
// , 9.52802903383275E9
// , 7.981295238889314E9
// , 1.9462480080050848E9
// . . .

This works because the 2nd parameter to the fill() method is "by-name", ie re-evaluated for every element.这是因为fill()方法的第二个参数是“按名称”,即为每个元素重新评估。


UPDATE更新

Things aren't quite as clean if you don't have the .between() method (Scala 2.13).如果你没有.between()方法(Scala 2.13),事情就不是那么干净了。

Array.fill(100)(rndm.nextDouble())
     .map(_ * math.pow(10,10))

Note that this actually has a floor of 0.0 instead of the desired 0.0000000001 .请注意,这实际上具有0.0而不是所需的0.0000000001的下限。 It's very unlikely you'd have an entry that's too small, especially when taking only 100 samples.您的条目不太可能太小,尤其是在仅采集 100 个样本时。 Still, there are steps you could take to insure that can't happen.不过,您可以采取一些措施来确保不会发生这种情况。

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

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