Skip to content

Commit afe3f9b

Browse files
committed
Support floattype(Rational) and guarantee AbstractFloat return
It seems to be a non-sequitur to allow `floattype` to return a type that is not an `AbstractFloat`. Breaking change: yes
1 parent 0c486f3 commit afe3f9b

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/FixedPointNumbers.jl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,15 @@ floatmax(::Type{T}) where {T <: FixedPoint} = typemax(T)
106106

107107

108108
"""
109-
floattype(::Type{T})
109+
floattype(::Type{T})::Type{<:AbstractFloat}
110110
111-
Return the minimum float type that represents `T` without overflow to `Inf`.
111+
Return a minimal `AbstractFloat` type suitable for performing computations with instances of type `T` without overflow to `Inf`.
112112
113113
# Example
114114
115115
A classic usage is to avoid overflow behavior by promoting `FixedPoint` to `AbstractFloat`
116116
117-
```julia
117+
```jldoctest
118118
julia> x = N0f8(1.0)
119119
1.0N0f8
120120
@@ -128,12 +128,13 @@ julia> float_x + float_x
128128
2.0f0
129129
```
130130
"""
131-
floattype(::Type{T}) where {T <: Real} = T # fallback
131+
floattype(::Type{T}) where {T <: AbstractFloat} = T # fallback (deliberately get MethodError if no method producing AbstractFloat defined)
132132
floattype(::Type{T}) where {T <: Union{ShortInts, Bool}} = Float32
133133
floattype(::Type{T}) where {T <: Integer} = Float64
134134
floattype(::Type{T}) where {T <: LongInts} = BigFloat
135135
floattype(::Type{X}) where {T <: ShortInts, X <: FixedPoint{T}} = Float32
136136
floattype(::Type{X}) where {T <: Integer, X <: FixedPoint{T}} = Float64
137+
floattype(::Type{X}) where {T <: Integer, X <: Rational{T}} = typeof(zero(T)/oneunit(T))
137138
floattype(::Type{X}) where {T <: LongInts, X <: FixedPoint{T}} = BigFloat
138139

139140
float(x::FixedPoint) = convert(floattype(x), x)

test/traits.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
using FixedPointNumbers, Test
2+
3+
struct MyReal <: Real end
4+
15
@testset "floattype" begin
26
function _is_fixed_type(x::Symbol)
37
try
@@ -16,4 +20,7 @@
1620
for T in exact_types
1721
@test typemax(T) <= maxintfloat(floattype(T))
1822
end
23+
@test floattype(Rational{Int}) === Float64
24+
25+
@test_throws MethodError floattype(MyReal)
1926
end

0 commit comments

Comments
 (0)