Skip to content

Commit

Permalink
linspace: "lift" linspace the way float ranges are [close #9637]
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKarpinski committed Jan 7, 2015
1 parent cf6bd1e commit 480f552
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
25 changes: 24 additions & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,36 @@ function linspace(start::Real, stop::Real, n::Integer)
end
n -= 1
S = promote_type(T, Float64)
for i=0:n
for i = 0:n
a[i+1] = start*(convert(S, (n-i))/n) + stop*(convert(S, i)/n)
end
a
end
linspace(start::Real, stop::Real) = linspace(start, stop, 100)

function linspace{T<:FloatingPoint}(start::T, stop::T, n::Int)
n == 1 && return [start]
n -= 1
a0, b = rat(start)
a = convert(T,a0)
if a/convert(T,b) == start
c0, d = rat(stop)
c = convert(T,c0)
if c/convert(T,d) == stop
e = lcm(b,d)
a *= div(e,b)
c *= div(e,d)
ne = convert(T,n*e)
if a*n/ne == start && c*n/ne == stop
return [ (a*(n-k) + c*k)/ne for k=0:n ]
end
end
end
return [ start*((n-k)/n) + stop*(k/n) for k=0:n ]
end
linspace(start::FloatingPoint, stop::FloatingPoint, n::Integer) =
linspace(promote(start, stop)..., Int(n))

logspace(start::Real, stop::Real, n::Integer) = 10.^linspace(start, stop, n)
logspace(start::Real, stop::Real) = logspace(start, stop, 50)

Expand Down
4 changes: 3 additions & 1 deletion test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,10 @@ for T = (Float32, Float64,),# BigFloat),
start = convert(T,a)/den
step = convert(T,s)/den
stop = convert(T,(a+(n-1)*s))/den
vals = T[a:s:a+(n-1)*s]./den
r = start:step:stop
@test [r] == T[a:s:a+(n-1)*s]./den
@test [r] == vals
@test linspace(start, stop, n) == vals
# issue #7420
n = length(r)
@test [r[1:n]] == [r]
Expand Down

0 comments on commit 480f552

Please sign in to comment.