Skip to content

Commit

Permalink
Add midpoints, which was deprecated in Base. (#345)
Browse files Browse the repository at this point in the history
* Add midpoints, which was deprecated in Base.

Currently not exported, to avoid symbol conflict.

* Add a methodless midpoints function for the definitions below.

* Changes suggested by @nalimilan.

Import midpoints for pre-v0.7, otherwise use unqualified symbol.

* Use more precise version

* Dividing by 2, to avoid accidental promotion.

Suggestion by @andreasnoack.
  • Loading branch information
tpapp authored and andreasnoack committed Feb 12, 2018
1 parent 43b5023 commit dffd8ae
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/src/misc.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ inverse_rle
levelsmap
indexmap
indicatormat
midpoints
```
4 changes: 4 additions & 0 deletions src/StatsBase.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ module StatsBase
using Printf
end

if VERSION < v"0.7.0-DEV.3335"
import Base: midpoints
end

## tackle compatibility issues

export
Expand Down
9 changes: 9 additions & 0 deletions src/hist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -524,3 +524,12 @@ have the same binning, shape of weights and properties (`closed` and
weights of the resulting histogram will have the same type as those of `h`.
"""
Base.merge(h::Histogram, others::Histogram...) = merge!(zero(h), h, others...)

"""
midpoints(v)
Calculate the midpoints (pairwise mean of consecutive elements).
"""
midpoints(v::AbstractVector) = [middle(v[i - 1], v[i]) for i in 2:length(v)]

midpoints(r::Range) = r[1:(end - 1)] + step(r) / 2
4 changes: 4 additions & 0 deletions test/hist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -226,5 +226,9 @@ end
@test (@inferred merge(histograms...)) == h
end

@testset "midpoints" begin
@test midpoints([1, 2, 4]) == [1.5, 3.0]
@test midpoints(linspace(0, 1, 5)) == 0.125:0.25:0.875
end

end # @testset "StatsBase.Histogram"

0 comments on commit dffd8ae

Please sign in to comment.