From d147f9253aa0f2f71be9c3fed8d51c2215410408 Mon Sep 17 00:00:00 2001 From: Milan Bouchet-Valat Date: Tue, 3 Oct 2023 21:33:47 +0200 Subject: [PATCH] Fix `quantile` with `Date` and `DateTime` (#153) Before #145 `Date` and `DateTime` were supported with `quantile` as long as the cut point falls between two equal values. Restore this behavior as some code may rely on this given that it is the most common situation with large datasets. --- Project.toml | 3 ++- src/Statistics.jl | 4 ++-- test/runtests.jl | 13 ++++++++++++- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Project.toml b/Project.toml index e8c16141..837a004f 100644 --- a/Project.toml +++ b/Project.toml @@ -10,8 +10,9 @@ LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [extras] +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Random", "Test"] +test = ["Dates", "Random", "Test"] diff --git a/src/Statistics.jl b/src/Statistics.jl index 25da1110..9baae597 100644 --- a/src/Statistics.jl +++ b/src/Statistics.jl @@ -1022,8 +1022,8 @@ end # When a ≉ b, b-a may overflow # When a ≈ b, (1-γ)*a + γ*b may not be increasing with γ due to rounding - # Call to float is to work around JuliaLang/julia#50380 - if isfinite(a) && isfinite(b) && float(a) ≈ float(b) + if isfinite(a) && isfinite(b) && + (!(a isa Number) || !(b isa Number) || a ≈ b) return a + γ*(b-a) else return (1-γ)*a + γ*b diff --git a/test/runtests.jl b/test/runtests.jl index 6599b46d..44fd849a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Statistics, Test, Random, LinearAlgebra, SparseArrays +using Statistics, Test, Random, LinearAlgebra, SparseArrays, Dates using Test: guardseed Random.seed!(123) @@ -770,6 +770,17 @@ end @test issorted(quantile([1.0, 1.0+2eps(), 1.0+4eps(), 1.0+6eps()], range(0, 1, length=100))) end +@testset "quantiles with Date and DateTime" begin + # this is the historical behavior + @test quantile([Date(2023, 09, 02)], .1) == Date(2023, 09, 02) + @test quantile([Date(2023, 09, 02), Date(2023, 09, 02)], .1) == Date(2023, 09, 02) + @test_throws InexactError quantile([Date(2023, 09, 02), Date(2023, 09, 03)], .1) + + @test quantile([DateTime(2023, 09, 02)], .1) == DateTime(2023, 09, 02) + @test quantile([DateTime(2023, 09, 02), DateTime(2023, 09, 02)], .1) == DateTime(2023, 09, 02) + @test_throws InexactError quantile([DateTime(2023, 09, 02), DateTime(2023, 09, 03)], .1) +end + @testset "variance of complex arrays (#13309)" begin z = rand(ComplexF64, 10) @test var(z) ≈ invoke(var, Tuple{Any}, z) ≈ cov(z) ≈ var(z,dims=1)[1] ≈ sum(abs2, z .- mean(z))/9