Skip to content

Instantly share code, notes, and snippets.

@navicore
Created December 11, 2017 16:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save navicore/7973711f300f00f9d878026eaf84bed2 to your computer and use it in GitHub Desktop.
Save navicore/7973711f300f00f9d878026eaf84bed2 to your computer and use it in GitHub Desktop.
standard deviation scala
import Numeric.Implicits._

def mean[T: Numeric](xs: Iterable[T]): Double = xs.sum.toDouble / xs.size

def variance[T: Numeric](xs: Iterable[T]): Double = {
  val avg = mean(xs)

  xs.map(_.toDouble).map(a => math.pow(a - avg, 2)).sum / xs.size
}

def stdDev[T: Numeric](xs: Iterable[T]): Double = math.sqrt(variance(xs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment