diff --git a/base/range.jl b/base/range.jl index 68132adca7d9f..48d60ab52a7fb 100644 --- a/base/range.jl +++ b/base/range.jl @@ -153,6 +153,12 @@ function frange{T<:FloatingPoint}(start::T, step::T, stop::T) start, step, one(step), floor(r)+1 end +colon{T<:FloatingPoint}(start::T, step::T, stop::T) = + step == 0 ? error("step cannot be zero in colon syntax") : + start == stop ? FloatRange{T}(start,step,1,1) : + (0 < step) != (start < stop) ? FloatRange{T}(start,step,1,0) : + FloatRange{T}(frange(start,step,stop)...) + similar(r::Ranges, T::Type, dims::Dims) = Array(T, dims) length(r::Ranges) = integer(r.len) diff --git a/test/ranges.jl b/test/ranges.jl index e9b72251b1df9..1870f4e8fe4e3 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -165,3 +165,48 @@ end @test all(((5:-1:1) + [1:5]) .== 6) @test all(([1:5] - (1:5)) .== 0) @test all(((1:5) - [1:5]) .== 0) + +# tricky floating-point ranges + +@test 0.1:0.1:0.3 == [1:3]./10 +@test 0.0:0.1:0.3 == [0:3]./10 +@test 0.3:-0.1:-0.1 == [3:-1:-1]./10 +@test 0.1:-0.1:-0.3 == [1:-1:-3]./10 +@test 0.0:0.1:1.0 == [0:10]./10 +@test 0.0:-0.1:1.0 == [] +@test 0.0:0.1:-1.0 == [] +@test 0.0:-0.1:-1.0 == [0:-1:-10]./10 +@test 1.0:1/49:27.0 == [49:1323]./49 +@test 0.0:0.7:2.1 == [0:7:21]./10 +@test 0.0:1.1:3.3 == [0:11:33]./10 +@test 0.1:1.1:3.4 == [1:11:34]./10 +@test 0.0:1.3:3.9 == [0:13:39]./10 +@test 0.1:1.3:4.0 == [1:13:40]./10 +@test 1.1:1.1:3.3 == [11:11:33]./10 +@test 0.3:0.1:1.1 == [3:1:11]./10 + +@test 0.0:1.0:5.5 == [0:10:55]./10 +@test 0.0:-1.0:0.5 == [] +@test 0.0:1.0:0.5 == [0.0] + +@test prevfloat(0.1):0.1:0.3 == [prevfloat(0.1), 0.2, 0.3] +@test nextfloat(0.1):0.1:0.3 == [nextfloat(0.1), 0.2] +@test prevfloat(0.0):0.1:0.3 == [prevfloat(0.0), 0.1, 0.2] +@test nextfloat(0.0):0.1:0.3 == [nextfloat(0.0), 0.1, 0.2] +@test 0.1:0.1:prevfloat(0.3) == [0.1, 0.2] +@test 0.1:0.1:nextfloat(0.3) == [0.1, 0.2, nextfloat(0.3)] +@test 0.0:0.1:prevfloat(0.3) == [0.0, 0.1, 0.2] +@test 0.0:0.1:nextfloat(0.3) == [0.0, 0.1, 0.2, nextfloat(0.3)] +@test 0.1:prevfloat(0.1):0.3 == [0.1, 0.2, 0.3] +@test 0.1:nextfloat(0.1):0.3 == [0.1, 0.2] +@test 0.0:prevfloat(0.1):0.3 == [0.0, prevfloat(0.1), prevfloat(0.2), 0.3] +@test 0.0:nextfloat(0.1):0.3 == [0.0, nextfloat(0.1), nextfloat(0.2)] + +for T = (Float32, Float64,),# BigFloat), + a = -5:25, s = [-5:-1;1:25], d = 1:25, n = -1:15 + den = convert(T,d) + start = convert(T,a)/den + step = convert(T,s)/den + stop = convert(T,(a+(n-1)*s))/den + @test [start:step:stop] == T[a:s:a+(n-1)*s]./den +end