From d7b017bcb84a76f0212ee6c8372818f34728091d Mon Sep 17 00:00:00 2001 From: Stefan Karpinski Date: Fri, 31 Jan 2014 20:54:21 -0500 Subject: [PATCH] FloatRange: hook new type up to colon syntax [fixes #2333]. --- base/range.jl | 6 ++++++ test/ranges.jl | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/base/range.jl b/base/range.jl index 68132adca7d9fe..48d60ab52a7fb4 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 07f94a25bcd432..8e46d5174594ca 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -159,3 +159,48 @@ else @test sum(int64(1:10^9)) == div(10^9 * (int64(10^9)+1), 2) @test sum(int64(1:10^9-1)) == div(10^9 * (int64(10^9)-1), 2) end + +# 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