Skip to content

Commit

Permalink
add bincenters for AbstractVector
Browse files Browse the repository at this point in the history
  • Loading branch information
jw3126 committed Jun 2, 2022
1 parent 063482b commit d07881a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/RangeHelpers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,21 @@ function bincenters(r::AbstractRange)::AbstractRange
return binwalls(r, first=false, last=false)
end

function bincenters(v::AbstractVector)
if isempty(v)
throw(ArgumentError("Cannot compute bincenters of empty vector."))
end
Base.require_one_based_indexing(v)
T = float(eltype(v))
ret = similar(v, T, length(v)-1)
half = T(1/2)
for i in 1:length(ret)
@inbounds m = half*(T(v[i]) + T(v[i+1]))
@inbounds ret[i] = m
end
return ret
end

################################################################################
##### subdivide
################################################################################
Expand Down
9 changes: 9 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,22 @@ end
@test RH.bincenters(1:2:9) == [2,4,6,8]
@inferred RH.bincenters(1:3)
@inferred RH.binwalls(1:3)

@test_throws ArgumentError bincenters(Int[])
@test bincenters([1]) == Float64[]
@test bincenters([10,20]) Float64[15]
@test eltype(bincenters(Float32[1])) === Float32
@test eltype(bincenters(Float64[1])) === Float64
@test bincenters([0,1,2,4]) [0.5, 1.5, 3]
end

@testset "searchsortedat" begin
@test RH.searchsortedat(10:10:30, RH.around(-100)) === 1
@test RH.searchsortedat(10:10:30, RH.around(5)) === 1
@test RH.searchsortedat(10:10:30, RH.around(10)) === 1
@test RH.searchsortedat(10:10:30, RH.around(14)) === 1
@test RH.searchsortedat(10:10:30, RH.around(14.99999999)) === 1
@test RH.searchsortedat(10:10:30, RH.around(15.00000001)) === 2
@test RH.searchsortedat(10:10:30, RH.around(16.0)) === 2
@test RH.searchsortedat(10:10:30, RH.around(20.0)) === 2
@test RH.searchsortedat(10:10:30, RH.around(24.0)) === 2
Expand Down

0 comments on commit d07881a

Please sign in to comment.