Skip to content

Commit 315e5cb

Browse files
NHDalyomus
authored andcommitted
Make FD÷FD return an FD. (#40)
* Make FD÷FD return an FD. Before this, `FD{T,f} ÷ FD{T,f}` returned `T`, now it returns `FD{T,f}`. Same for `div`, `fld`, and `fld`. * Add some simple unit tests for ÷ There weren't any tests of `div` before, so this adds some simple ones. * Add comment explaining why div() doesn't need widening logic * Fix div (÷) tests to actually test output type * Include explicit test of Return Types
1 parent 07d24d9 commit 315e5cb

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/FixedPointDecimals.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,9 @@ for remfn in [:rem, :mod, :mod1, :min, :max]
300300
@eval $remfn(x::T, y::T) where {T <: FD} = reinterpret(T, $remfn(x.i, y.i))
301301
end
302302
for divfn in [:div, :fld, :fld1]
303-
@eval $divfn(x::T, y::T) where {T <: FD} = $divfn(x.i, y.i)
303+
# div(x.i, y.i) eliminates the scaling coefficient, so we call the FD constructor.
304+
# We don't need any widening logic, since we won't be multiplying by the coefficient.
305+
@eval $divfn(x::T, y::T) where {T <: FD} = T($divfn(x.i, y.i))
304306
end
305307

306308
convert(::Type{AbstractFloat}, x::FD) = convert(floattype(typeof(x)), x)

test/runtests.jl

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,36 @@ end
508508
end
509509
end
510510

511+
@testset "truncating div" begin
512+
@testset "div by 1" begin
513+
@testset for x in keyvalues[FD2]
514+
@test x ÷ one(x) === trunc(x)
515+
516+
# signed integers using two's complement have one additional negative value
517+
if x < 0 && trunc(x) === typemin(x)
518+
@test_throws InexactError x ÷ -one(x)
519+
else
520+
@test x ÷ -one(x) === -trunc(x)
521+
end
522+
end
523+
end
524+
@testset "div by 2" begin
525+
@testset for x in keyvalues[FD2]
526+
@test x ÷ 2one(x) === x ÷ 2 === FD2(x.i ÷ FD2(2).i)
527+
end
528+
end
529+
@testset "return types" begin
530+
@test div(2one(FD2), 3) isa FD2
531+
@test one(FD2) ÷ one(FD2) isa FD2
532+
533+
# Promotion to bigger type
534+
@test one(FD4) ÷ one(FD2) isa FD4
535+
@test one(FD2) ÷ one(FD4) isa FD4
536+
537+
@test one(FD{Int32, 2}) ÷ one(FD{Int64, 6}) isa FD{Int64, 6}
538+
end
539+
end
540+
511541
@testset "abs, sign" begin
512542
@testset for T in [FD2, WFD4]
513543
for x in keyvalues[T]

0 commit comments

Comments
 (0)