Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @file:Suppress("SameParameterValue")
- /* Typealiases.kt:
- package com.sooby.stats
- typealias Uniform = Double
- typealias Normal = Double
- typealias PairList<A, B> = List<Pair<A, B>>
- */
- package com.sooby.stats
- import kotlin.random.Random
- import kotlin.math.*
- object NormalEq {
- private fun box(ua: Uniform, ub: Uniform): Pair<Normal, Normal> = (2.0 * PI * ub).let { theta ->
- sqrt(-2.0 * ln(ua)).let { r ->
- r * cos(theta) to r * sin(theta)
- }
- }
- private fun normalvariate(): Pair<Normal, Normal> = box(Random.nextDouble(), Random.nextDouble())
- private fun addMuSigma(z: Normal, mu: Double, sigma: Double): Normal = (z * sigma) + mu
- private fun normalvariate(mu: Double, sigma: Double): Pair<Normal, Normal> = normalvariate().let { (za, zb) ->
- addMuSigma(za, mu, sigma) to addMuSigma(zb, mu, sigma)
- }
- /**
- * don't use this for anything that could overflow or underflow.
- */
- @JvmName("roundPairs")
- fun PairList<Double, Double>.roundAll(): List<Pair<Int, Int>> = this.map { (ra, rb) ->
- round(ra).toInt() to round(rb).toInt()
- }
- // fun List<Double>.roundAll(): List<Int> = this.map { round(it).toInt() }
- private fun <A : Any> PairList<A, A>.flatten(): List<A> = this.map { listOf(it.first, it.second) }.flatten()
- private fun <C : Comparable<C>> List<C>.countDistinct(): PairList<C, Int> = this.distinct().sorted().map { c ->
- c to this.count { it == c }
- }
- private fun <A : Any> PairList<A, A>.countEq(): Pair<Int, Int> =
- this.partition { it.first == it.second }.let { it.first.size to it.second.size }
- fun main() {
- println((0.until(10000)).map {normalvariate(100.0, 10.0)}.roundAll().let { roundedRandoms ->
- ( roundedRandoms.countEq().let {"Equal: ${it.first}; not equal: ${it.second}"}
- to roundedRandoms.flatten().countDistinct().joinToString ("\n") { (value, count) ->
- "Number equaling $value: $count"
- }
- ).let { (eqResult, catResult) ->
- "$eqResult\n$catResult"
- }
- }
- )
- }
- }
- fun main() {
- NormalEq.main()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement