Skip to content

Commit

Permalink
FloatRange: hook new type up to colon syntax [fixes #2333].
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKarpinski committed Feb 24, 2014
1 parent 47a3447 commit f4905d9
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
6 changes: 6 additions & 0 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
45 changes: 45 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit f4905d9

Please sign in to comment.