Skip to content

Commit 4153c6b

Browse files
authored
fix negative integer powers (#95)
1 parent dbcedf6 commit 4153c6b

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/DecFP.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,13 @@ function Base.sqrt(z::Complex{T}) where {T<:DecimalFloatingPoint}
494494
Complex(ξ,η)
495495
end
496496

497+
# see issue #92 — the fallback power_by_squaring fails for p < 0, and this is more accurate:
498+
Base.:^(x::DecimalFloatingPoint, p::Integer) = x^oftype(x, p)
499+
@inline Base.literal_pow(::typeof(^), x::DecimalFloatingPoint, ::Val{0}) = one(x)
500+
@inline Base.literal_pow(::typeof(^), x::DecimalFloatingPoint, ::Val{1}) = x
501+
@inline Base.literal_pow(::typeof(^), x::DecimalFloatingPoint, ::Val{2}) = x*x
502+
@inline Base.literal_pow(::typeof(^), x::DecimalFloatingPoint, ::Val{3}) = x*x*x
503+
497504
# used for next/prevfloat:
498505
const pinf128 = _parse(Dec128, "+Inf")
499506
const minf128 = _parse(Dec128, "-Inf")

test/runtests.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,16 @@ for T in (Dec32, Dec64, Dec128)
147147
@test xd == Tf(x) == T(Tf(x)) == Tf(xd)
148148
end
149149

150+
# issue #92
151+
p = -2
152+
@test T(2)^-2 == parse(T, "0.25") == T(2)^p
153+
154+
# exercise literal_pow
155+
@test T(2)^0 === T(1)
156+
@test T(2)^1 === T(2)
157+
@test T(2)^2 === T(4)
158+
@test T(2)^3 === T(8)
159+
150160
@test trunc(T(2.7)) === floor(T(2.7)) === round(T(2.7), RoundDown) === round(T(2.7), RoundToZero) === T(2)
151161
@test ceil(T(2.3)) === round(T(2.3), RoundUp) === round(T(2.3), RoundFromZero) === T(3)
152162
@test round(T(1.5)) === round(T(2.5)) === round(T(1.5), RoundNearest) === round(T(2.5), RoundNearest) === T(2)

0 commit comments

Comments
 (0)