Skip to content

Commit 2439cc9

Browse files
authored
relax type definition of middle (#28)
* relax type definition of middle this adds support for computing the median of unitful types, see JuliaPhysics/Unitful.jl#202 * updates docs and add tests for middle on non-reals
1 parent 327eed8 commit 2439cc9

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

src/Statistics.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -733,17 +733,17 @@ cor(x::AbstractVecOrMat, y::AbstractVecOrMat; dims::Int=1) =
733733
Compute the middle of a scalar value, which is equivalent to `x` itself, but of the type of `middle(x, x)` for consistency.
734734
"""
735735
middle(x::Union{Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128}) = Float64(x)
736-
# Specialized functions for real types allow for improved performance
736+
# Specialized functions for number types allow for improved performance
737737
middle(x::AbstractFloat) = x
738-
middle(x::Real) = (x + zero(x)) / 1
738+
middle(x::Number) = (x + zero(x)) / 1
739739

740740
"""
741741
middle(x, y)
742742
743-
Compute the middle of two reals `x` and `y`, which is
743+
Compute the middle of two numbers `x` and `y`, which is
744744
equivalent in both value and type to computing their mean (`(x + y) / 2`).
745745
"""
746-
middle(x::Real, y::Real) = x/2 + y/2
746+
middle(x::Number, y::Number) = x/2 + y/2
747747

748748
"""
749749
middle(range)

test/runtests.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ Random.seed!(123)
1414
@test middle(1:8) === 4.5
1515
@test middle([1:8;]) === 4.5
1616

17+
@test middle(5.0 + 2.0im, 2.0 + 3.0im) == 3.5 + 2.5im
18+
@test middle(5.0 + 2.0im) == 5.0 + 2.0im
19+
1720
# ensure type-correctness
1821
for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64]
1922
@test middle(one(T)) === middle(one(T), one(T))

0 commit comments

Comments
 (0)