Advertisement
SoobNauce

NormalEq.kt

Apr 3rd, 2022
1,220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.19 KB | None | 0 0
  1. @file:Suppress("SameParameterValue")
  2.  
  3. /* Typealiases.kt:
  4. package com.sooby.stats
  5. typealias Uniform = Double
  6. typealias Normal = Double
  7. typealias PairList<A, B> = List<Pair<A, B>>
  8. */
  9.  
  10. package com.sooby.stats
  11.  
  12. import kotlin.random.Random
  13. import kotlin.math.*
  14.  
  15. object NormalEq {
  16.     private fun box(ua: Uniform, ub: Uniform): Pair<Normal, Normal> = (2.0 * PI * ub).let { theta ->
  17.         sqrt(-2.0 * ln(ua)).let { r ->
  18.             r * cos(theta) to r * sin(theta)
  19.         }
  20.     }
  21.  
  22.     private fun normalvariate(): Pair<Normal, Normal> = box(Random.nextDouble(), Random.nextDouble())
  23.  
  24.     private fun addMuSigma(z: Normal, mu: Double, sigma: Double): Normal = (z * sigma) + mu
  25.  
  26.     private fun normalvariate(mu: Double, sigma: Double): Pair<Normal, Normal> = normalvariate().let { (za, zb) ->
  27.         addMuSigma(za, mu, sigma) to addMuSigma(zb, mu, sigma)
  28.     }
  29.  
  30.     /**
  31.      * don't use this for anything that could overflow or underflow.
  32.      */
  33.     @JvmName("roundPairs")
  34.     fun PairList<Double, Double>.roundAll(): List<Pair<Int, Int>> = this.map { (ra, rb) ->
  35.         round(ra).toInt() to round(rb).toInt()
  36.     }
  37.  
  38.     // fun List<Double>.roundAll(): List<Int> = this.map { round(it).toInt() }
  39.  
  40.     private fun <A : Any> PairList<A, A>.flatten(): List<A> = this.map { listOf(it.first, it.second) }.flatten()
  41.  
  42.     private fun <C : Comparable<C>> List<C>.countDistinct(): PairList<C, Int> = this.distinct().sorted().map { c ->
  43.         c to this.count { it == c }
  44.     }
  45.  
  46.     private fun <A : Any> PairList<A, A>.countEq(): Pair<Int, Int> =
  47.         this.partition { it.first == it.second }.let { it.first.size to it.second.size }
  48.  
  49.     fun main() {
  50.         println((0.until(10000)).map {normalvariate(100.0, 10.0)}.roundAll().let { roundedRandoms ->
  51.             ( roundedRandoms.countEq().let {"Equal: ${it.first}; not equal: ${it.second}"}
  52.                     to roundedRandoms.flatten().countDistinct().joinToString ("\n") { (value, count) ->
  53.                 "Number equaling $value: $count"
  54.             }
  55.                     ).let { (eqResult, catResult) ->
  56.                     "$eqResult\n$catResult"
  57.                 }
  58.         }
  59.         )
  60.     }
  61. }
  62. fun main() {
  63.     NormalEq.main()
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement