Skip to content

Commit 6f8a7d3

Browse files
committed
Fix a type-stability problem for linspace
1 parent 999a4ff commit 6f8a7d3

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

base/twiceprecision.jl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ end
309309
## StepRangeLen
310310

311311
# Use TwicePrecision only for Float64; use Float64 for T<:Union{Float16,Float32}
312+
# See also _linspace1
312313
# Ratio-of-integers constructors
313314
function steprangelen_hp(::Type{Float64}, ref::Tuple{Integer,Integer},
314315
step::Tuple{Integer,Integer}, nb::Integer,
@@ -651,7 +652,12 @@ function _linspace1(::Type{T}, start, stop, len::Integer) where T
651652
if len <= 1
652653
len == 1 && (start == stop || throw(ArgumentError("linspace($start, $stop, $len): endpoints differ")))
653654
# Ensure that first(r)==start and last(r)==stop even for len==0
654-
return StepRangeLen(TwicePrecision(start, zero(T)), TwicePrecision(start, -stop), len, 1)
655+
# The output type must be consistent with steprangelen_hp
656+
if T<:Union{Float32,Float16}
657+
return StepRangeLen{T}(Float64(start), Float64(start) - Float64(stop), len, 1)
658+
else
659+
return StepRangeLen(TwicePrecision(start, zero(T)), TwicePrecision(start, -stop), len, 1)
660+
end
655661
end
656662
throw(ArgumentError("should only be called for len < 2, got $len"))
657663
end

test/ranges.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,9 @@ end
204204
@test L32[3] == 3 && L64[3] == 3
205205
@test L32[4] == 4 && L64[4] == 4
206206
@test @inferred(linspace(1.0, 2.0, 2.0f0)) === linspace(1.0, 2.0, 2)
207+
@test @inferred(linspace(1.0, 2.0, 2))[1] === 1.0
208+
@test @inferred(linspace(1.0f0, 2.0f0, 2))[1] === 1.0f0
209+
@test @inferred(linspace(Float16(1.0), Float16(2.0), 2))[1] === Float16(1.0)
207210

208211
let r = 5:-1:1
209212
@test r[1]==5

0 commit comments

Comments
 (0)