Random.nextDouble所在位置是kotlin.random.Random.nextDouble,其相關用法介紹如下。

用法一

open fun nextDouble(): Double
fun nextDouble(): Double

獲取下一個隨機 Double 值,均勻分布在 0(包括)和 1(不包括)之間。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
if (Random.nextDouble() <= 0.3) {
    println("There was 30% possibility of rainy weather today and it is raining.")
} else {
    println("There was 70% possibility of sunny weather today and the sun is shining.")
}
//sampleEnd
}

輸出:

There was 70% possibility of sunny weather today and the sun is shining.

用法二

open fun nextDouble(until: Double): Double
fun nextDouble(until: Double): Double

從隨機數生成器中獲取小於指定 until 界限的下一個隨機非負 Double

生成在 0(包括)和 until(不包括)之間均勻分布的 Double 隨機值。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val firstAngle = Random.nextDouble(until = Math.PI / 6);
println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true

val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2)
val sinValue = sin(secondAngle)
println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true
//sampleEnd
}

輸出:

sin(firstAngle) < 0.5 is true
sinValue >= 0.5 && sinValue < 1.0 is true

異常

IllegalArgumentException- 如果直到是負數或零。

用法三

open fun nextDouble(from: Double, until: Double): Double
fun nextDouble(from: Double, until: Double): Double

從指定範圍內的隨機數生成器中獲取下一個隨機Double

生成在指定的from(包括)和until(不包括)邊界之間均勻分布的Double 隨機值。

fromuntil 必須是有限的,否則行為未指定。

例子:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val firstAngle = Random.nextDouble(until = Math.PI / 6);
println("sin(firstAngle) < 0.5 is ${sin(firstAngle) < 0.5}") // true

val secondAngle = Random.nextDouble(from = Math.PI / 6, until = Math.PI / 2)
val sinValue = sin(secondAngle)
println("sinValue >= 0.5 && sinValue < 1.0 is ${sinValue >= 0.5 && sinValue < 1.0}") // true
//sampleEnd
}

輸出:

sin(firstAngle) < 0.5 is true
sinValue >= 0.5 && sinValue < 1.0 is true

異常

IllegalArgumentException- 如果大於或等於直到.