From 14facf1f68d44425c6d3fc30eea7e80551960b72 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 2 Oct 2026 22:44:12 +0000 Subject: [PATCH] fix: Seq.meanTruncatedBy trims both ends Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/FSharp.Stats/Seq.fs | 6 +++--- tests/FSharp.Stats.Tests/Seq.fs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/FSharp.Stats/Seq.fs b/src/FSharp.Stats/Seq.fs index 3cf9dc50..74e9f16f 100644 --- a/src/FSharp.Stats/Seq.fs +++ b/src/FSharp.Stats/Seq.fs @@ -323,18 +323,18 @@ module Seq = /// /// /// let values = [1.0; 2.0; 3.0; 4.0; 5.0] - /// let m = Seq.meanTruncatedBy (fun x -> x * 2.0) 0.2 values // returns 7.0 + /// let m = Seq.meanTruncatedBy (fun x -> x * 2.0) 0.2 values // returns 6.0 /// /// let inline meanTruncatedBy (f : 'T -> ^U) (proportion:float) (data:seq<'T>) : 'U = let zero = LanguagePrimitives.GenericZero< 'U > let n = Seq.length(data) if (n > 0) then - let k = int (floor (float n * proportion)) + let k = int (float n * proportion) data |> Seq.sort |> Seq.skip k - |> Seq.take (n - k) + |> Seq.take (n - 2 * k) |> meanBy f else diff --git a/tests/FSharp.Stats.Tests/Seq.fs b/tests/FSharp.Stats.Tests/Seq.fs index c91e0ad0..e25b5e90 100644 --- a/tests/FSharp.Stats.Tests/Seq.fs +++ b/tests/FSharp.Stats.Tests/Seq.fs @@ -396,6 +396,22 @@ let seqGenTests = ] +[] +let meanTruncatedByTests = + testList "Seq.meanTruncatedBy" [ + testCase "trims both ends" <| fun () -> + let xs = [1.0 .. 10.0] + // k = 2: keeps 3..8, doubled mean = 11.0 + Expect.floatClose Accuracy.high (Seq.meanTruncatedBy (fun x -> x * 2.0) 0.2 xs) 11.0 "Expected both ends trimmed" + testCase "matches meanTruncated for identity" <| fun () -> + let xs = [9.0; 1.0; 4.0; 100.0; -50.0; 3.0; 7.0; 2.0; 8.0; 5.0] + Expect.floatClose Accuracy.high (Seq.meanTruncatedBy id 0.2 xs) (Seq.meanTruncated 0.2 xs) "Expected equal results" + testCase "zero proportion equals mean" <| fun () -> + let xs = [1.0; 2.0; 3.0; 4.0] + Expect.floatClose Accuracy.high (Seq.meanTruncatedBy id 0.0 xs) 2.5 "Expected plain mean" + ] + + [] let varTests = testList "Seq.var" [