ulrich ulrich - 1 month ago 6x
Scala Question

Generating a list of double/decimales in Scala

I can generate a list of random values using the following code

val foo = Seq.fill(3)(scala.util.Random.nextInt(100))

but how can I have a list of value between 0 and 1 instead?

I tried


but it produces a list of Int

Seq[Int] = List(0, 0, 0)


As long as either the divisor or the dividend is a Double, you have numeric widening implicit conversions which will automatically convert the other argument also to a double. Otherwise, the division is considered as integer division.

scala> val foo = Seq.fill(3)(scala.util.Random.nextInt(1000)/1000.toDouble)
foo: Seq[Double] = List(0.44, 0.836, 0.426)

That said, you should use nextDouble if you want this behavior - it generates a random double between 0 and 1

scala> val foo = Seq.fill(3)(scala.util.Random.nextDouble)
foo: Seq[Double] = List(0.9016195186022057, 0.32388738824301755, 0.09844453536156428)