Skip to content

Commit

Permalink
add trunc methods to BigInt, fixes JuliaLang#13367
Browse files Browse the repository at this point in the history
  • Loading branch information
simonbyrne committed Sep 30, 2015
1 parent e1f6dbb commit b31925c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
16 changes: 13 additions & 3 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Base: *, +, -, /, <, <<, >>, >>>, <=, ==, >, >=, ^, (~), (&), (|), ($),
binomial, cmp, convert, div, divrem, factorial, fld, gcd, gcdx, lcm, mod,
ndigits, promote_rule, rem, show, isqrt, string, isprime, powermod,
sum, trailing_zeros, trailing_ones, count_ones, base, tryparse_internal,
bin, oct, dec, hex, isequal, invmod, prevpow2, nextpow2, ndigits0z, widen, signed
bin, oct, dec, hex, isequal, invmod, prevpow2, nextpow2, ndigits0z, widen, signed, unsafe_trunc, trunc

if Clong == Int32
typealias ClongMax Union{Int8, Int16, Int32}
Expand Down Expand Up @@ -120,13 +120,23 @@ end

convert(::Type{BigInt}, x::Bool) = BigInt(UInt(x))

function convert(::Type{BigInt}, x::Float64)
!isinteger(x) && throw(InexactError())

function unsafe_trunc(::Type{BigInt}, x::CdoubleMax)
z = BigInt()
ccall((:__gmpz_set_d, :libgmp), Void, (Ptr{BigInt}, Cdouble), &z, x)
return z
end

function convert(::Type{BigInt}, x::CdoubleMax)
isinteger(x) || throw(InexactError())
unsafe_trunc(BigInt,x)
end

function trunc(::Type{BigInt}, x::CdoubleMax)
isfinite(x) || throw(InexactError())
unsafe_trunc(BigInt,x)
end

convert(::Type{BigInt}, x::Float16) = BigInt(Float64(x))
convert(::Type{BigInt}, x::Float32) = BigInt(Float64(x))

Expand Down
16 changes: 16 additions & 0 deletions test/bigint.jl
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,19 @@ ndigits_mismatch(n) = ndigits(n) != ndigits(BigInt(n))
@test BigInt(2.0) == BigInt(2.0f0) == BigInt(big(2.0)) == 2
@test_throws InexactError convert(BigInt, 2.1)
@test_throws InexactError convert(BigInt, big(2.1))

# issue #13367
@test trunc(BigInt,2.1) == 2
@test round(BigInt,2.1) == 2
@test floor(BigInt,2.1) == 2
@test ceil(BigInt,2.1) == 3

@test trunc(BigInt,2.1f0) == 2
@test round(BigInt,2.1f0) == 2
@test floor(BigInt,2.1f0) == 2
@test ceil(BigInt,2.1f0) == 3

@test_throws InexactError trunc(BigInt,Inf)
@test_throws InexactError round(BigInt,Inf)
@test_throws InexactError floor(BigInt,Inf)
@test_throws InexactError ceil(BigInt,Inf)

0 comments on commit b31925c

Please sign in to comment.