// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) import kotlin.math.* import java.util.Random // extension methods fun DoubleArray.transform(f: (Double) -> Double): DoubleArray = this.map({ xi -> f(xi) }).toDoubleArray() fun DoubleArray.transform(y: DoubleArray, f: (Double, Double) -> Double): DoubleArray = this.zip(y, { xi, yi -> f(xi, yi) }).toDoubleArray() // RNG val rng = Random() fun unirng(): Double = rng.nextDouble() fun normrng(): Double = sqrt(-2 * ln(unirng())) * cos(2 * PI * unirng()) // stat functions fun expect(x: DoubleArray): Double = x.sum() / x.count() fun avg(x: DoubleArray): Double = expect(x) fun vari(x: DoubleArray): Double = expect(x.transform({ xi -> xi.pow(2) - avg(x).pow(2) })) fun stdev(x: DoubleArray): Double = sqrt(vari(x)) fun covari(x: DoubleArray, y: DoubleArray): Double = expect(x.transform(y, {xi, yi -> (xi - avg(x)) * (yi - avg(y)) })) fun corr(x: DoubleArray, y: DoubleArray): Double = covari(x, y) / (stdev(x) * stdev(y)) // sequence generation fun initRandom(n: Int): DoubleArray = DoubleArray(n, { _ -> normrng() }) // test val SIZE = 1000 fun testone(n: Int): Double { val data = Array(SIZE, { _ -> initRandom(n) }) var total = 0 var overhalf = 0 for(i in 0..(SIZE-1)) { for(j in (i+1)..(SIZE-1)) { total++ if(corr(data[i], data[j]) >= 0.5) overhalf++ } } return overhalf * 1.0 / total } val REP = 100 fun test(n: Int) { val res = DoubleArray(REP, { _ -> testone(n) }) println("n = %d : prob corr > 0.5 = %.4f (+/- %.4f)".format(n, avg(res), stdev(res))) } fun main() { test(10) test(20) test(30) test(40) test(50) }