1

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?

1 Answer 1

5

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", i.e. 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. But I am getting following error
error: value between is not a member of scala.util.Random
scala version "2.11.12"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.