Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/fixed.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,10 @@ rem(x::Integer, ::Type{Fixed{T,f}}) where {T,f} = Fixed{T,f}(rem(x,T)<<f,0)
rem(x::Real, ::Type{Fixed{T,f}}) where {T,f} = Fixed{T,f}(rem(Integer(trunc(x)),T)<<f + rem(Integer(round(rem(x,1)*(one(widen1(T))<<f))),T),0)


Base.BigFloat(x::Fixed{T,f}) where {T,f} =
BigFloat(x.i>>f) + BigFloat(x.i&(one(widen1(T))<<f - 1))/BigFloat(one(widen1(T))<<f)
(::Type{TF})(x::Fixed{T,f}) where {TF <: AbstractFloat,T,f} =
TF(x.i>>f) + TF(x.i&(one(widen1(T))<<f - 1))/TF(one(widen1(T))<<f)
(::Type{Tf})(x::Fixed{T,f}) where {Tf <: AbstractFloat, T, f} = Tf(Tf(x.i) * Tf(@exp2(-f)))
Base.Float16(x::Fixed{T,f}) where {T, f} = Float16(Float32(x))
Base.Float32(x::Fixed{T,f}) where {T, f} = Float32(x.i) * Float32(@exp2(-f))
Base.Float64(x::Fixed{T,f}) where {T, f} = Float64(x.i) * @exp2(-f)

function Base.Rational(x::Fixed{T,f}) where {T, f}
f < bitwidth(T)-1 ? x.i//rawone(x) : x.i//(one(widen1(T))<<f)
Expand Down
37 changes: 37 additions & 0 deletions test/fixed.jl
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,43 @@ end
@test isa(float(one(Fixed{Int32,25})), Float64)
end

@testset "conversions to float" begin
for T in (Float16, Float32, Float64, BigFloat)
@test isa(convert(T, Q0f7(0.3)), T)
end

for Tf in (Float16, Float32, Float64)
@testset "$Tf(::Fixed{$T})" for T in (Int8, Int16)
@testset "$Tf(::Fixed{$T,$f})" for f = 0:bitwidth(T)-1
F = Fixed{T,f}
float_err = 0.0
for i = typemin(T):typemax(T)
f_expected = Tf(i * BigFloat(2)^-f)
f_actual = Tf(reinterpret(F, i))
float_err += abs(f_actual - f_expected)
end
@test float_err == 0.0
end
end
@testset "$Tf(::Fixed{$T})" for T in (Int32, Int64, Int128)
@testset "$Tf(::Fixed{$T,$f})" for f = 0:bitwidth(T)-1
F = Fixed{T,f}
error_count = 0
for i in vcat(typemin(T):(typemin(T)+0xFF),
-T(0xFF):T(0xFF),
(typemax(T)-0xFF):typemax(T))
f_expected = Tf(i * BigFloat(2)^-f)
isinf(f_expected) && break # for Float16() and Float32()
f_actual = Tf(reinterpret(F, i))
f_actual == f_expected && continue
error_count += 1
end
@test error_count == 0
end
end
end
end

@testset "predicates" begin
@test isfinite(1Q7f8)
@test !isnan(1Q7f8)
Expand Down