Skip to content

Commit

Permalink
add efficient mean and median for ranges
Browse files Browse the repository at this point in the history
  • Loading branch information
stevengj committed Aug 22, 2014
1 parent 8609056 commit 27fe81d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
==========================

Expand Down Expand Up @@ -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
17 changes: 17 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 27fe81d

Please sign in to comment.