Skip to content

Commit 2bf80f2

Browse files
committed
Improve performance of max_exp10
1 parent 373e002 commit 2bf80f2

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/FixedPointDecimals.jl

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,19 @@ end
393393
The highest value of `x` which does not result in an overflow when evaluating `T(10)^x`.
394394
"""
395395
function max_exp10{T <: Integer}(::Type{T})
396-
length(digits(typemax(T))) - 1
396+
W = widen(T)
397+
type_max = W(typemax(T))
398+
399+
powt = one(W)
400+
ten = W(10)
401+
exponent = 0
402+
403+
while type_max > powt
404+
powt *= ten
405+
exponent += 1
406+
end
407+
408+
exponent - 1
397409
end
398410

399411
"""

test/runtests.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,21 @@ if VERSION < v"0.6.0-dev.1849"
7474
Base.:/(x::UInt128, y::BigInt) = /(promote(x, y)...)
7575
end
7676

77+
@testset "max_exp10" begin
78+
@test FixedPointDecimals.max_exp10(Int8) == 2
79+
@test FixedPointDecimals.max_exp10(Int64) == 18
80+
@test FixedPointDecimals.max_exp10(Int128) == 38
81+
@test FixedPointDecimals.max_exp10(UInt8) == 2
82+
@test FixedPointDecimals.max_exp10(UInt64) == 19
83+
@test FixedPointDecimals.max_exp10(UInt128) == 38
84+
@test_throws MethodError FixedPointDecimals.max_exp10(BigInt)
85+
86+
for T in CONTAINER_TYPES
87+
x = FixedPointDecimals.max_exp10(T)
88+
@test T(10)^x == widen(T(10))^x
89+
end
90+
end
91+
7792
# ensure that the coefficient multiplied by the highest and lowest representable values of
7893
# the container type do not result in overflow.
7994
@testset "coefficient" begin

0 commit comments

Comments
 (0)