From 2065842b27e499543c753557bb97eaa2c742ee7e Mon Sep 17 00:00:00 2001 From: Stefan Karpinski Date: Wed, 8 Feb 2017 22:14:15 -0500 Subject: [PATCH] float ranges: for ambiguous length, use round((stop-start)/step)+1 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. --- base/twiceprecision.jl | 13 ++++++++++--- test/ranges.jl | 3 ++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/base/twiceprecision.jl b/base/twiceprecision.jl index 23cc2690f5b44..5c0b4f210aca9 100644 --- a/base/twiceprecision.jl +++ b/base/twiceprecision.jl @@ -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 diff --git a/test/ranges.jl b/test/ranges.jl index 67fc58ae55c85..9dc4c82884c2e 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -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)