Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add efficient mean and median for ranges #8089

Merged
merged 2 commits into from
Aug 24, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 ([#8011]).

* Efficient `mean` and `median` for ranges ([#8089]).

Julia v0.3.0 Release Notes
==========================

Expand Down Expand Up @@ -948,3 +950,4 @@ Too numerous to mention.
[#7917]: https://github.com/JuliaLang/julia/issues/7917
[#7992]: https://github.com/JuliaLang/julia/issues/7992
[#8011]: https://github.com/JuliaLang/julia/issues/8011
[#8089]: https://github.com/JuliaLang/julia/issues/8089
7 changes: 7 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,13 @@ 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

median{T<:Real}(r::Range{T}) = mean(r)

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