Skip to content

Commit

Permalink
float ranges: for ambiguous length, use round((stop-start)/step)+1
Browse files Browse the repository at this point in the history
Fixes #20532 by defining which length to use when there's more than
one length that is compatible with a given start:step:stop combo.
This also tightens the tests to check for that specific result.
  • Loading branch information
StefanKarpinski committed Feb 9, 2017
1 parent b7ad743 commit 2065842
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
13 changes: 10 additions & 3 deletions base/twiceprecision.jl
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,16 @@ function colon{T<:Union{Float16,Float32,Float64}}(start::T, step::T, stop::T)
end
end
# Fallback, taking start and step literally
len = max(0, floor(Int, (stop-start)/step) + 1)
stop′ = start + len*step
len += (start < stop′ <= stop) + (start > stop′ >= stop)
lf = (stop-start)/step
if lf < 0
len = 0
elseif lf == 0
len = 1
else
len = round(Int, lf) + 1
stop′ = start + (len-1)*step
len -= (start < stop < stop′) + (start > stop > stop′)
end
StepRangeLen(TwicePrecision(start, zero(T)), twiceprecision(step, nbitslen(T, len, 1)), len)
end

Expand Down
3 changes: 2 additions & 1 deletion test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,9 @@ for T = (Float32, Float64,), i = 1:2^15, n = 1:5
lo = hi = n
while start + (lo-1)*step == stop; lo -= 1; end
while start + (hi-1)*step == stop; hi += 1; end
m = clamp(round(Int, (stop-start)/step) + 1, lo+1, hi-1)
r = start:step:stop
@test lo < length(r) < hi
@test m == length(r)
# FIXME: these fail some small portion of the time
@test_skip start == first(r)
@test_skip stop == last(r)
Expand Down

0 comments on commit 2065842

Please sign in to comment.