From 27fe81db7016be451512c5a71517bb2f4a16ffce Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Fri, 22 Aug 2014 13:01:20 -0400 Subject: [PATCH] add efficient mean and median for ranges --- NEWS.md | 3 +++ base/range.jl | 17 +++++++++++++++++ test/ranges.jl | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/NEWS.md b/NEWS.md index 23b8921e78108e..b9011d537f071a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -25,6 +25,8 @@ Library improvements intend to use the default `Forward` order, or `pq = PriorityQueue(KeyType, ValueType, OrderType)` otherwise. + * Efficient `mean` and `median` for ranges ([#8089]). + Julia v0.3.0 Release Notes ========================== @@ -947,3 +949,4 @@ Too numerous to mention. [#7654]: https://github.com/JuliaLang/julia/issues/7654 [#7917]: https://github.com/JuliaLang/julia/issues/7917 [#7992]: https://github.com/JuliaLang/julia/issues/7992 +[#8089]: https://github.com/JuliaLang/julia/issues/8089 diff --git a/base/range.jl b/base/range.jl index 85ed100b3dded4..5193078b3631d0 100644 --- a/base/range.jl +++ b/base/range.jl @@ -553,6 +553,23 @@ function sum{T<:Real}(r::Range{T}) : (step(r) * l) * ((l-1)>>1)) end + +function mean{T<:Real}(r::Range{T}) + isempty(r) && error("mean of an empty range is undefined") + (first(r) + last(r)) / 2 +end + +function median{T<:Real}(r::Range{T}) + isempty(r) && error("median of an empty range is undefined") + n = length(r) + if iseven(n) + mid = n >> 1 + return (r[mid] + r[mid+1]) / 2 + else # odd + return float(r[(n+1)>>1]) + end +end + function map!(f::Callable, dest, r::Range) i = 1 for ri in r dest[i] = f(ri); i+=1; end diff --git a/test/ranges.jl b/test/ranges.jl index 3102b8dc4f9b7a..d860f229aff84b 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -350,3 +350,11 @@ end @test length(map(identity, 0x0001:0x0005)) == 5 @test length(map(identity, uint64(1):uint64(5))) == 5 @test length(map(identity, uint128(1):uint128(5))) == 5 + +# mean/median +for f in (mean, median) + for n = 2:5 + @test f(2:n) == f([2:n]) + @test_approx_eq f(2:0.1:n) f([2:0.1:n]) + end +end