Skip to content

Commit

Permalink
Merge pull request #8089 from stevengj/rangemean
Browse files Browse the repository at this point in the history
add efficient mean and median for ranges
  • Loading branch information
andreasnoack committed Aug 24, 2014
2 parents 333e18c + e552d25 commit a08ae29
Show file tree
Hide file tree
Showing 3 changed files with 18 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 ([#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

0 comments on commit a08ae29

Please sign in to comment.