Last active
September 21, 2018 04:09
-
-
Save Pooh3Mobi/c23a6311f684447e3d6d8502bde4ecf7 to your computer and use it in GitHub Desktop.
Kotlinized ChiSquareTestDemo (https://github.com/komiya-atsushi/dbflute-fes-2014-demo/blob/master/src/main/java/biz/k11i/demo/stat/ChiSquareTestDemo.java)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import org.apache.commons.math3.stat.inference.ChiSquareTest | |
import java.util.Random | |
/** | |
* カイ二乗検定のデモ | |
* https://github.com/komiya-atsushi/dbflute-fes-2014-demo/blob/master/src/main/java/biz/k11i/demo/stat/ChiSquareTestDemo.java | |
* Kotlin ver | |
*/ | |
fun main(args: Array<String>) { | |
val rnd = SecureRandom() | |
val times = 100000 | |
val alpha = 0.05 | |
rnd.run(rollFairDice(times)) | |
.let(doChiSqTest(alpha)) | |
.also(printChiSqTestResult("Fair Dice test", alpha)) | |
rnd.run(rollUnfairDice(times)) | |
.let(doChiSqTest(alpha)) | |
.also(printChiSqTestResult("Unfair Dice test", alpha)) | |
} | |
private fun rollFairDice(times: Int): (Random) -> LongArray = { rnd -> | |
LongArray(6).apply { | |
for (i in 0 until times) { | |
this[rnd.nextInt(6)]++ | |
} | |
} | |
} | |
private fun rollUnfairDice(times: Int): (Random) -> LongArray = { rnd -> | |
LongArray(6).apply { | |
for (i in 0 until times) { | |
this[if (i % 10 == 0) { | |
0 | |
} else { | |
rnd.nextInt(6) | |
}]++ | |
} | |
} | |
} | |
private fun doChiSqTest(alpha: Double): (LongArray) -> Pair<LongArray, Boolean> = | |
{ observed -> | |
observed to ChiSquareTest().chiSquareTest( | |
DoubleArray(6).apply { fill(1.0 / 6) }, | |
observed, alpha | |
) | |
} | |
private fun printChiSqTestResult(tag: String, alpha: Double): (Pair<LongArray, Boolean>) -> Unit = | |
{ (observed, isFitted) -> | |
println( ("[%s]有意水準 %.3f%% での観測結果 %s のカイ二乗検定の結果は %s です。\n" + | |
if (isFitted) "よって「さいころの各目が出る確率が等しい」という帰無仮説は棄却されます" | |
else "よって「さいころの各目が出る確率が等しい」という帰無仮説は棄却されません").format( | |
tag, | |
alpha * 100, | |
observed.contentToString(), | |
isFitted | |
).let { | |
if (isFitted) it.toAnsiRed() else it | |
}) | |
} | |
const val ANSI_RED = "\u001B[31m" | |
const val ANSI_RESET = "\u001B[0m" | |
fun Any?.toAnsiRed() = ANSI_RED + this + ANSI_RESET |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment