Created
July 29, 2013 08:38
-
-
Save aktau/6102979 to your computer and use it in GitHub Desktop.
benchmark averaging methods
This file contains 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
def movingRunningApprox(window: Int, l: Seq[Int]) = { | |
val N = window | |
val seedrun = l.take(N) | |
var avg = seedrun.sum / seedrun.length | |
println(l) | |
val xs = l map { el => | |
val (pre,dec,inc) = (avg,avg/N,el/N) | |
avg = avg - avg/N + el/N | |
println(s"$avg = $pre - $dec + $inc") | |
avg | |
} toList | |
xs.drop(window - 1) | |
} | |
def movingRunningReal(window: Int, l: Seq[Int]) = { | |
val N = window | |
println(l) | |
l.sliding(N).map { slice => | |
println(slice) | |
slice.sum / slice.length | |
} toList | |
} | |
def comparem(window: Int, l: Seq[Int]) = { | |
val approx = movingRunningApprox(window,l) | |
val real = movingRunningReal(window,l) | |
val diff = (approx zip real) map { case (a,r) => r - a } | |
val reldiff = (approx zip real) map { | |
case (a,r) => (math.abs(r - a).toDouble / math.abs(r).toDouble) * 100 | |
} map { | |
scala.math.BigDecimal(_).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble | |
} | |
(approx, real, diff, reldiff) | |
} | |
def benchm(w: Int, n: Int, s: Int) = { | |
val randlists = (1 to n) map { _ => Seq.fill(s)(scala.util.Random.nextInt / 1000) } | |
val sz = randlists.length | |
println(s"generated $n lists of size $s (check $sz)") | |
randlists zip (randlists map { comparem(w, _) }) | |
} | |
benchm(15, 5, 20) foreach { case (source, avgs) => | |
println(source) | |
println(avgs._1.length, avgs._2.length, avgs._3.length, avgs._4.length) | |
val length = avgs._1.length | |
println(s"iterating from 0 to $length") | |
for (i <- 0 until length) { | |
val (approx, real, diff, reldiff) = (avgs._1(i), avgs._2(i), avgs._3(i), avgs._4(i)) | |
println(s"a: $approx\t<-> r: $real\t(diff: $diff,\trel: $reldiff)") | |
} | |
// println(s"$source => $avgs") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment