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

Implement rounding in length(::StepRange) #18744

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Make range work better with roundoff error
  • Loading branch information
timholy committed Oct 1, 2016
commit 4d7aaf7902b90526dfbbf1c2d54093eacf1360d5
11 changes: 10 additions & 1 deletion base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,16 @@ colon{T}(start::T, step, stop::T) = StepRange(start, step, stop)

Construct a range by length, given a starting value and optional step (defaults to 1).
"""
range{T,S}(a::T, step::S, len::Integer) = StepRange{T,S}(a, step, convert(T, a+step*(len-1)))
function range{T,S}(a::T, step::S, len::Integer)
r = StepRange{T,S}(a, step, convert(T, a+step*(len-1)))
if length(r) < len
r = StepRange{T,S}(a, step, convert(T, a+step*len))
if length(r) > len
throw(InexactError())
end
end
r
end

## floating point ranges

Expand Down
6 changes: 5 additions & 1 deletion test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -794,8 +794,9 @@ Base.isless(x::FloatLike, y::FloatLike) = isless(x.val, y.val)
Base.:+(x::FloatLike, y::FloatLike) = FloatLike(x.val+y.val)
Base.:-(x::FloatLike, y::FloatLike) = FloatLike(x.val-y.val)
Base.:/(x::FloatLike, y::FloatLike) = x.val / y.val
# Base.div(x::FloatLike, y::FloatLike) = div(x.val, y.val)
Base.rem(x::FloatLike, y::FloatLike) = FloatLike(rem(x.val, y.val))
Base.:*(x::FloatLike, y::Int) = FloatLike(x.val * y)
Base.:/(x::FloatLike, y::Int) = FloatLike(x.val / y)

rf = 0.8:0.8:640.0
rs = StepRange(FloatLike(0.8), FloatLike(0.8), FloatLike(640))
Expand All @@ -807,3 +808,6 @@ rs = StepRange(FloatLike(640), FloatLike(-0.8), FloatLike(0.8))
@test first(rs) == FloatLike(640)
@test last(rs).val ≈ 0.8
@test length(rf) == length(rs) == 800
rs = range(FloatLike(0), FloatLike(0.1), 10)
@test length(rs) == 10
@test last(rs).val ≈ 0.9