Skip to content

Commit

Permalink
relax type definition of middle (#28)
Browse files Browse the repository at this point in the history
* relax type definition of middle

this adds support for computing the median of unitful types, see PainterQubits/Unitful.jl#202

* updates docs and add tests for middle on non-reals
  • Loading branch information
tlnagy authored Oct 8, 2020
1 parent 327eed8 commit 2439cc9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -733,17 +733,17 @@ cor(x::AbstractVecOrMat, y::AbstractVecOrMat; dims::Int=1) =
Compute the middle of a scalar value, which is equivalent to `x` itself, but of the type of `middle(x, x)` for consistency.
"""
middle(x::Union{Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128}) = Float64(x)
# Specialized functions for real types allow for improved performance
# Specialized functions for number types allow for improved performance
middle(x::AbstractFloat) = x
middle(x::Real) = (x + zero(x)) / 1
middle(x::Number) = (x + zero(x)) / 1

"""
middle(x, y)
Compute the middle of two reals `x` and `y`, which is
Compute the middle of two numbers `x` and `y`, which is
equivalent in both value and type to computing their mean (`(x + y) / 2`).
"""
middle(x::Real, y::Real) = x/2 + y/2
middle(x::Number, y::Number) = x/2 + y/2

"""
middle(range)
Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Random.seed!(123)
@test middle(1:8) === 4.5
@test middle([1:8;]) === 4.5

@test middle(5.0 + 2.0im, 2.0 + 3.0im) == 3.5 + 2.5im
@test middle(5.0 + 2.0im) == 5.0 + 2.0im

# ensure type-correctness
for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64]
@test middle(one(T)) === middle(one(T), one(T))
Expand Down

0 comments on commit 2439cc9

Please sign in to comment.