Skip to content

Commit 9d2876c

Browse files
committed
implement sample median
1 parent 862bda5 commit 9d2876c

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/main/scala/statistics.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,11 @@ object Statistics:
4040
val xty = Matrix.mul(x.transpose, Matrix.makeRowMatrix(y))
4141
val beta = Matrix.mul(Matrix.inverse(xtx), xty)
4242
beta(0)
43+
44+
def median(x: Vec): Double =
45+
val L = x.length
46+
val sorted = x.sorted
47+
L match
48+
case n if n % 2 == 0 => (sorted(n / 2 - 1) + sorted(n / 2)) / 2.0
49+
case _ => sorted(L / 2)
50+

src/test/scala/teststatistics.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,5 +70,16 @@ class TestStatistics extends munit.FunSuite {
7070
val expected = Array(1.0, 2.0)
7171
A.assert(Matrix.elementwise_equal(beta, expected, 1e-6))
7272
}
73+
test("Median"){
74+
val x = Array(1.0, 2.0, 3.0, 4.0, 5.0)
75+
val median = Statistics.median(x)
76+
val expected = 3.0
77+
A.assertEqualsDouble(median, expected, 1e-6)
78+
79+
val y = Array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0).reverse
80+
val median2 = Statistics.median(y)
81+
val expected2 = 3.5
82+
A.assertEqualsDouble(median2, expected2, 1e-6)
83+
}
7384

7485
}

0 commit comments

Comments
 (0)