Generate a random double in Kotlin
This article explores different ways to generate a random double in Kotlin.
1. Using Random.nextDouble() function
The standard solution to generate a pseudorandom uniformly-distributed double value is using the Random.nextDouble() function. It generates a random value between 0.0 (inclusive) and 1.0 (exclusive) with a random number generator (RNG).
|
1 2 3 4 5 6 |
import kotlin.random.Random fun main() { val random = Random.nextDouble() println(random) } |
To generate a pseudorandom uniformly-distributed double value in the specified range, we can do as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import kotlin.random.Random fun getRandom(min: Int, max: Int): Double { require(min < max) { "Invalid range [$min, $max]" } return min + Random.nextDouble() * (max - min) } fun main() { val min = 0 val max = 10 val random = getRandom(min, max) println(random) } |
2. Using Random.nextFloat() function
The kotlin.random.Random class provides the corresponding functions to generate pseudorandom values for Integer, Long, Double, Float, Boolean, etc. To generate a pseudorandom float value between 0.0f (inclusive) and 1.0f (exclusive), we can call the Random.nextFloat() function.
|
1 2 3 4 5 6 |
import kotlin.random.Random fun main() { val random = Random.nextFloat() println(random) } |
Additionally, we can extend the solution to work with the specified range:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import kotlin.random.Random fun getRandom(min: Int, max: Int): Double { require(min < max) { "Invalid range [$min, $max]" } return (min + Random.nextFloat() * (max - min)).toDouble() } fun main() { val min = 0 val max = 10 val random = getRandom(min, max) println(random) } |
3. Using Math.random() function
Alternatively, we can use the Math.random() function to generate a pseudorandom double value. It returns a uniformly distributed value between 0.0 (inclusive) and 1.0 (exclusive).
|
1 2 3 4 |
fun main() { val random = Math.random() println(random) } |
As with previous methods, we can easily extend the solution to any range:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun getRandom(min: Int, max: Int): Double { require(min < max) { "Invalid range [$min, $max]" } return min + Math.random() * (max - min) } fun main() { val min = 0 val max = 10 val random = getRandom(min, max) println(random) } |
That’s all about generating a random double in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)