Skip to content

Commit 3d9332b

Browse files
committed
Convert from Rational to FD must be exact
1 parent 05137bc commit 3d9332b

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

src/FixedPointDecimals.jl

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -211,12 +211,8 @@ end
211211
convert{T <: FD}(::Type{T}, x::AbstractFloat) = round(T, x)
212212

213213
function convert{T, f}(::Type{FD{T, f}}, x::Rational)::FD{T, f}
214-
powt = T(10)^f
215-
num::T, den::T = numerator(x), denominator(x)
216-
g = gcd(powt, den)
217-
powt = div(powt, g)
218-
den = div(den, g)
219-
reinterpret(FD{T, f}, powt * num) / FD{T, f}(den)
214+
powt = coefficient(FD{T, f})
215+
reinterpret(FD{T, f}, T(x * powt))
220216
end
221217

222218
function convert{T, f, U, g}(::Type{FD{T, f}}, x::FD{U, g})

test/runtests.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,13 @@ end
116116
@test min_int >= typemin(T)
117117
@test value(convert(FD{T,f}, min_int / powt)) == min_int
118118

119+
@test convert(FD{T,f}, typemax(T) // powt) == reinterpret(FD{T,f}, typemax(T))
120+
@test convert(FD{T,f}, typemin(T) // powt) == reinterpret(FD{T,f}, typemin(T))
121+
119122
@test_throws InexactError convert(FD{T,f}, T(1))
120123

121124
# Adjust number of decimal places allowed so we can have `-10 < x < 10` where x is
122-
# a FD{T,f}.
125+
# a FD{T,f}. Only needed to test `convert(::FD, ::Integer)`
123126
f = FixedPointDecimals.max_exp10(T)
124127
powt = FixedPointDecimals.coefficient(FD{T,f})
125128

@@ -136,6 +139,8 @@ end
136139
@test_throws InexactError convert(FD2, FD4(0.0001))
137140
@test_throws InexactError convert(FD4, typemax(FD2))
138141
@test_throws InexactError convert(SFD2, typemax(FD2))
142+
@test_throws InexactError convert(FD2, 1//3)
143+
@test_throws InexactError convert(FD{Int8,1}, 1//4)
139144
end
140145

141146
@testset "promotion" begin

0 commit comments

Comments
 (0)