Random.nextDouble
所在位置是kotlin.random.Random.nextDouble
,其相關用法介紹如下。
用法一
獲取下一個隨機 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.
用法二
從隨機數生成器中獲取小於指定 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
- 如果直到是負數或零。
用法三
從指定範圍內的隨機數生成器中獲取下一個隨機Double
。
生成在指定的from(包括)和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
異常
相關用法
- Kotlin Random.nextBytes用法及代碼示例
- Kotlin Random.nextInt用法及代碼示例
- Kotlin Random.nextBoolean用法及代碼示例
- Kotlin Random.nextBits用法及代碼示例
- Kotlin Random.nextFloat用法及代碼示例
- Kotlin Random.nextLong用法及代碼示例
- Kotlin Random.Default用法及代碼示例
- Kotlin Random.<init>用法及代碼示例
- Kotlin Random用法及代碼示例
- Kotlin Regex.matchAt用法及代碼示例
- Kotlin Regex.splitToSequence用法及代碼示例
- Kotlin Regex.matchesAt用法及代碼示例
- Kotlin Regex.find用法及代碼示例
- Kotlin Regex.findAll用法及代碼示例
- Kotlin associateBy用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin map用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin reduceRight用法及代碼示例
- Kotlin Byte.inc用法及代碼示例
- Kotlin getValue用法及代碼示例
- Kotlin Double.dec用法及代碼示例
- Kotlin windowedSequence用法及代碼示例
- Kotlin contentToString用法及代碼示例
- Kotlin groupByTo用法及代碼示例
注:本文由純淨天空篩選整理自kotlinlang.org大神的英文原創作品 kotlin.random.Random.nextDouble。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。