Skip to content

Commit

Permalink
linspace: handle very large *and* very small endpoints correctly.
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKarpinski committed Apr 2, 2015
1 parent 171ac3f commit 0e13a1e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
18 changes: 12 additions & 6 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -193,17 +193,23 @@ function linspace{T<:FloatingPoint}(start::T, stop::T, len::Int)
e = lcm(b,d)
a *= div(e,b)
c *= div(e,d)
s, p = frexp(convert(T,n*e))
p = one(p) << p
a /= p; c /= p
s = convert(T,n*e)
if isinf(a*n) || isinf(c*n)
s, p = frexp(convert(T,s))
p = one(p) << p
a /= p; c /= p
end
if a*n/s == start && c*n/s == stop
return LinSpace(a, c, len, s)
end
end
end
s, p = frexp(convert(T,n))
p = one(p) << p
start /= p; stop /= p
s = convert(T,n)
if isinf(s*start) || isinf(s*stop)
s, p = frexp(s)
p = one(p) << p
start /= p; stop /= p
end
return LinSpace(start, stop, len, s)
end
linspace(start::Real, stop::Real, len::Real=50) =
Expand Down
21 changes: 21 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,27 @@ for T = (Float32, Float64,),# BigFloat),
@test [r[n:-2:1];] == [r;][n:-2:1]
end

# very small linspace & ranges
for T = (Float32, Float64)
z = zero(T)
u = eps(z)
@test [linspace(-u,u,2);] == [-u,u]
@test [linspace(-u,u,3);] == [-u,0,u]
@test [linspace(-u,u,4);] == [-u,0,0,u]
@test [linspace(-u,u,4);][2] === -z
@test [linspace(-u,u,4);][3] === z
@test [linspace(u,-u,2);] == [u,-u]
@test [linspace(u,-u,3);] == [u,0,-u]
@test [linspace(u,-u,4);] == [u,0,0,-u]
@test [linspace(u,-u,4);][2] === z
@test [linspace(u,-u,4);][3] === -z
v = [linspace(-u,u,12);]
@test length(v) == 12
@test issorted(v) && unique(v) == [-u,0,0,u]
@test [-3u:u:3u;] == [linspace(-3u,3u,7);] == [-3:3;].*u
@test [3u:-u:-3u;] == [linspace(3u,-3u,7);] == [3:-1:-3;].*u
end

# near-equal ranges
@test 0.0:0.1:1.0 != 0.0f0:0.1f0:1.0f0

Expand Down

0 comments on commit 0e13a1e

Please sign in to comment.