// 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)) // detrend fun avgincr(x: DoubleArray): Double = expect(DoubleArray(x.size - 1, { i -> x[i + 1] - x[i] })) fun detrend(x: DoubleArray): DoubleArray = DoubleArray(x.size, { i -> x[i] - i * avgincr(x) }) // sequence generation fun initRandom(n: Int): DoubleArray = DoubleArray(n, { _ -> normrng() }) fun initRandomWithTrend(n: Int, trend: Double): DoubleArray = DoubleArray(n, { i -> trend * i + normrng() }) fun initNonRandom(x: DoubleArray): DoubleArray = DoubleArray(x.size, { i -> x[i] + normrng() }) // test val N = 100 fun test(trend: Double) { val f1 = initRandomWithTrend(N, trend) val f2 = initRandomWithTrend(N, trend) val f3 = initNonRandom(f1) val f1f2 = corr(f1, f2) val f1f3 = corr(f1, f3) val dtf1f2 = corr(detrend(f1), detrend(f2)) val dtf1f3 = corr(detrend(f1), detrend(f3)) println("f1 = $trend * i + N(0,1)") println("f2 = $trend * i + N(0,1)") println("f3 = f1 + N(0,1)") println("corr f1 f2 = $f1f2") println("corr f1 f3 = $f1f3") println("corr detrended f1 f2 = $dtf1f2") println("corr detrended f1 f3 = $dtf1f3") } fun main() { test(0.0) test(0.1) test(1.0) }