Skip to content

Commit ef72da9

Browse files
linspace: "lift" linspace the way float ranges are [close #9637]
1 parent cd85555 commit ef72da9

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

base/array.jl

+24-1
Original file line numberDiff line numberDiff line change
@@ -258,13 +258,36 @@ function linspace(start::Real, stop::Real, n::Integer)
258258
end
259259
n -= 1
260260
S = promote_type(T, Float64)
261-
for i=0:n
261+
for i = 0:n
262262
a[i+1] = start*(convert(S, (n-i))/n) + stop*(convert(S, i)/n)
263263
end
264264
a
265265
end
266266
linspace(start::Real, stop::Real) = linspace(start, stop, 100)
267267

268+
function linspace{T<:FloatingPoint}(start::T, stop::T, n::Int)
269+
n == 1 && return [start]
270+
n -= 1
271+
a0, b = rat(start)
272+
a = convert(T,a0)
273+
if a/convert(T,b) == start
274+
c0, d = rat(stop)
275+
c = convert(T,c0)
276+
if c/convert(T,d) == stop
277+
e = lcm(b,d)
278+
a *= div(e,b)
279+
c *= div(e,d)
280+
ne = convert(T,n*e)
281+
if a*n/ne == start && c*n/ne == stop
282+
return [ (a*(n-k) + c*k)/ne for k=0:n ]
283+
end
284+
end
285+
end
286+
return [ start*((n-k)/n) + stop*(k/n) for k=0:n ]
287+
end
288+
linspace(start::FloatingPoint, stop::FloatingPoint, n::Integer) =
289+
linspace(promote(start, stop)..., Int(n))
290+
268291
logspace(start::Real, stop::Real, n::Integer) = 10.^linspace(start, stop, n)
269292
logspace(start::Real, stop::Real) = logspace(start, stop, 50)
270293

test/ranges.jl

+3-1
Original file line numberDiff line numberDiff line change
@@ -272,8 +272,10 @@ for T = (Float32, Float64,),# BigFloat),
272272
start = convert(T,a)/den
273273
step = convert(T,s)/den
274274
stop = convert(T,(a+(n-1)*s))/den
275+
vals = T[a:s:a+(n-1)*s;]./den
275276
r = start:step:stop
276-
@test [r;] == T[a:s:a+(n-1)*s;]./den
277+
@test [r;] == vals
278+
@test linspace(start, stop, n) == vals
277279
# issue #7420
278280
n = length(r)
279281
@test [r[1:n];] == [r;]

0 commit comments

Comments
 (0)