statistics.nbt 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. use core::lists
  2. # TODO: remove these helpers once we support local definitions
  3. fn _max<D: Dim>(x: D, y: D) -> D = if x > y then x else y
  4. fn _min<D: Dim>(x: D, y: D) -> D = if x < y then x else y
  5. @name("Maxmimum")
  6. @description("Get the largest element of a list.")
  7. @example("maximum([30 cm, 2 m])")
  8. fn maximum<D: Dim>(xs: List<D>) -> D =
  9. if len(xs) == 1
  10. then head(xs)
  11. else _max(head(xs), maximum(tail(xs)))
  12. @name("Minimum")
  13. @description("Get the smallest element of a list.")
  14. @example("minimum([30 cm, 2 m])")
  15. fn minimum<D: Dim>(xs: List<D>) -> D =
  16. if len(xs) == 1
  17. then head(xs)
  18. else _min(head(xs), minimum(tail(xs)))
  19. @name("Arithmetic mean")
  20. @description("Calculate the arithmetic mean of a list of quantities.")
  21. @example("mean([1 m, 2 m, 300 cm])")
  22. @url("https://en.wikipedia.org/wiki/Arithmetic_mean")
  23. fn mean<D: Dim>(xs: List<D>) -> D = if is_empty(xs) then 0 else sum(xs) / len(xs)
  24. @name("Variance")
  25. @url("https://en.wikipedia.org/wiki/Variance")
  26. @description("Calculate the population variance of a list of quantities")
  27. @example("variance([1 m, 2 m, 300 cm])")
  28. fn variance<D: Dim>(xs: List<D>) -> D^2 =
  29. mean(map(sqr, xs)) - sqr(mean(xs))
  30. @name("Standard deviation")
  31. @url("https://en.wikipedia.org/wiki/Standard_deviation")
  32. @description("Calculate the population standard deviation of a list of quantities")
  33. @example("stdev([1 m, 2 m, 300 cm])")
  34. fn stdev<D: Dim>(xs: List<D>) -> D = sqrt(variance(xs))
  35. @name("Median")
  36. @url("https://en.wikipedia.org/wiki/Median")
  37. @description("Calculate the median of a list of quantities")
  38. @example("median([1 m, 2 m, 400 cm])")
  39. fn median<D: Dim>(xs: List<D>) -> D = # TODO: this is extremely inefficient
  40. if mod(n, 2) == 1
  41. then element_at((n - 1) / 2, sort(xs))
  42. else mean([element_at(n / 2 - 1, sort(xs)), element_at(n / 2, sort(xs))])
  43. where
  44. n = len(xs)