简体   繁体   中英

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. 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.

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.


UPDATE

Things aren't quite as clean if you don't have the .between() method (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 . It's very unlikely you'd have an entry that's too small, especially when taking only 100 samples. Still, there are steps you could take to insure that can't happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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