Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Created December 11, 2018 19:29
Show Gist options
  • Select an option

  • Save thomasnield/db440d8d7d401e63a72ed018525c7969 to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/db440d8d7d401e63a72ed018525c7969 to your computer and use it in GitHub Desktop.
Continuous Distribution Sampler
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.pow
fun pdf(x: Double) = 2 * x // y = 2x from 0 to 1 is probability distribution function
fun cdf(x: Double) = x.pow(2) // CDF plots area under PDF curve https://www.wolframalpha.com/input/?i=integral+2x
fun reverseCdf(a: Double) = a.pow(.5) // Reverse CDF to sample the area and the resuling x
fun main() {
(1..1000).asSequence()
.map { reverseCdf(ThreadLocalRandom.current().nextDouble(0.0,1.0)) }
.map { it to pdf(it) }
.forEach {
println("${it.first},${it.second}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment