Skip to content

Commit 5f0ab36

Browse files
committed
Merge pull request #31 from JeffBezanson/teh/reductions
Fix reductions so they don't overflow
2 parents 4c30ba6 + 060ab8c commit 5f0ab36

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

src/FixedPointNumbers.jl

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ module FixedPointNumbers
44

55
using Compat
66

7+
using Base: IdFun, AddFun, MulFun, reducedim_initarray
8+
79
import Base: ==, <, <=, -, +, *, /, ~,
810
convert, promote_rule, show, showcompact, isinteger, abs, decompose,
911
isnan, isinf, isfinite,
1012
zero, one, typemin, typemax, realmin, realmax, eps, sizeof, reinterpret,
1113
trunc, round, floor, ceil, bswap,
1214
div, fld, rem, mod, mod1, rem1, fld1, min, max,
13-
start, next, done
15+
start, next, done, r_promote, reducedim_init
1416
# T => BaseType
1517
# f => Number of Bytes reserved for fractional part
1618
abstract FixedPoint{T <: Integer, f} <: Real
@@ -60,6 +62,19 @@ include("ufixed.jl")
6062
include("deprecations.jl")
6163

6264

65+
# Promotions for reductions
66+
const Treduce = Float64
67+
for F in (AddFun, MulFun)
68+
@eval r_promote{T}(::$F, x::FixedPoint{T}) = Treduce(x)
69+
end
70+
71+
reducedim_init{T<:FixedPoint}(f::IdFun, op::AddFun,
72+
A::AbstractArray{T}, region) =
73+
reducedim_initarray(A, region, zero(Treduce))
74+
reducedim_init{T<:FixedPoint}(f::IdFun, op::MulFun,
75+
A::AbstractArray{T}, region) =
76+
reducedim_initarray(A, region, one(Treduce))
77+
6378
# TODO: rewrite this by @generated
6479
for T in tuple(Fixed16, UF...)
6580
R = rawtype(T)

test/fixed.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,16 @@ for (TI, f) in [(Int8, 8), (Int16, 8), (Int16, 10), (Int32, 16)]
5353
println(" Testing $T")
5454
test_fixed(T, f)
5555
end
56+
57+
# reductions
58+
F8 = Fixed{Int8,8}
59+
a = F8[0.498, 0.1]
60+
acmp = Float64(a[1]) + Float64(a[2])
61+
@test sum(a) == acmp
62+
@test sum(a, 1) == [acmp]
63+
64+
F6 = Fixed{Int8,6}
65+
a = F6[1.2, 1.4]
66+
acmp = Float64(a[1])*Float64(a[2])
67+
@test prod(a) == acmp
68+
@test prod(a, 1) == [acmp]

test/ufixed.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,13 @@ b, ad = scaledual(0.5, ad)
153153
generic_scale!(rfloat, a, 0.5)
154154
generic_scale!(rfixed, ad, b)
155155
@test rfloat == rfixed
156+
157+
# reductions
158+
a = UFixed8[0xffuf8, 0xffuf8]
159+
@test sum(a) == 2.0
160+
@test sum(a, 1) == [2.0]
161+
162+
a = UFixed14[3.2, 2.4]
163+
acmp = Float64(a[1])*Float64(a[2])
164+
@test prod(a) == acmp
165+
@test prod(a, 1) == [acmp]

0 commit comments

Comments
 (0)