Skip to content

Commit 0c19ae2

Browse files
linspace: try to "lift" linspace the float ranges are [close #9637]
1 parent cf6bd1e commit 0c19ae2

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
@@ -217,13 +217,36 @@ function linspace(start::Real, stop::Real, n::Integer)
217217
end
218218
n -= 1
219219
S = promote_type(T, Float64)
220-
for i=0:n
220+
for i = 0:n
221221
a[i+1] = start*(convert(S, (n-i))/n) + stop*(convert(S, i)/n)
222222
end
223223
a
224224
end
225225
linspace(start::Real, stop::Real) = linspace(start, stop, 100)
226226

227+
function linspace{T<:FloatingPoint}(start::T, stop::T, n::Int)
228+
n == 1 && return [start]
229+
n -= 1
230+
a0, b = rat(start)
231+
a = convert(T,a0)
232+
if a/convert(T,b) == start
233+
c0, d = rat(stop)
234+
c = convert(T,c0)
235+
if c/convert(T,d) == stop
236+
e = lcm(b,d)
237+
a *= div(e,b)
238+
c *= div(e,d)
239+
ne = convert(T,n*e)
240+
if a*n/ne == start && c*n/ne == stop
241+
return [ (a*(n-k) + c*k)/ne for k=0:n ]
242+
end
243+
end
244+
end
245+
return [ start*((n-k)/n) + stop*(k/n) for k=0:n ]
246+
end
247+
linspace(start::FloatingPoint, stop::FloatingPoint, n::Integer) =
248+
linspace(promote(start, stop)..., Int(n))
249+
227250
logspace(start::Real, stop::Real, n::Integer) = 10.^linspace(start, stop, n)
228251
logspace(start::Real, stop::Real) = logspace(start, stop, 50)
229252

test/ranges.jl

+3-1
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,10 @@ for T = (Float32, Float64,),# BigFloat),
248248
start = convert(T,a)/den
249249
step = convert(T,s)/den
250250
stop = convert(T,(a+(n-1)*s))/den
251+
vals = T[a:s:a+(n-1)*s]./den
251252
r = start:step:stop
252-
@test [r] == T[a:s:a+(n-1)*s]./den
253+
@test [r] == vals
254+
@test linspace(start, stop, n) == vals
253255
# issue #7420
254256
n = length(r)
255257
@test [r[1:n]] == [r]

0 commit comments

Comments
 (0)