Skip to content

Commit

Permalink
Merge pull request JuliaLang#10139 from simonbyrne/bigint-float
Browse files Browse the repository at this point in the history
Fix BigInt to Float conversions
  • Loading branch information
simonbyrne committed Mar 18, 2015
2 parents 17abcd9 + 930f875 commit 288ea08
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 4 deletions.
45 changes: 41 additions & 4 deletions base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,48 @@ if sizeof(Int64) == sizeof(Clong)
end
convert(::Type{Int128}, x::BigInt) = copysign(UInt128(abs(x))%Int128,x)

function convert(::Type{Float64}, n::BigInt)
# TODO: this should round to nearest but instead rounds to zero

function call(::Type{Float64}, n::BigInt, ::RoundingMode{:ToZero})
ccall((:__gmpz_get_d, :libgmp), Float64, (Ptr{BigInt},), &n)
end
convert(::Type{Float32}, n::BigInt) = Float32(Float64(n))
convert(::Type{Float16}, n::BigInt) = Float16(Float64(n))

function call{T<:Union(Float16,Float32)}(::Type{T}, n::BigInt, ::RoundingMode{:ToZero})
T(Float64(n,RoundToZero),RoundToZero)
end

function call{T<:CdoubleMax}(::Type{T}, n::BigInt, ::RoundingMode{:Down})
x = T(n,RoundToZero)
x > n ? prevfloat(x) : x
end
function call{T<:CdoubleMax}(::Type{T}, n::BigInt, ::RoundingMode{:Up})
x = T(n,RoundToZero)
x < n ? nextfloat(x) : x
end
function call{T<:CdoubleMax}(::Type{T}, n::BigInt, ::RoundingMode{:Nearest})
x = T(n,RoundToZero)
if maxintfloat(T) <= abs(x) < T(Inf)
r = n-BigInt(x)
h = eps(x)/2
if iseven(reinterpret(Unsigned,x)) # check if last bit is odd/even
if r < -h
return prevfloat(x)
elseif r > h
return nextfloat(x)
end
else
if r <= -h
return prevfloat(x)
elseif r >= h
return nextfloat(x)
end
end
end
x
end

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

rem(x::BigInt, ::Type{Bool}) = ((x&1)!=0)

Expand All @@ -216,6 +252,7 @@ function rem{T<:Integer}(n::BigInt, ::Type{T})
convert(T, (n-lo) & (widen(hi)-widen(lo)) + lo)
end


promote_rule{T<:Integer}(::Type{BigInt}, ::Type{T}) = BigInt

# serialization
Expand Down
12 changes: 12 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,18 @@ end
@test !(Float32(pi,RoundDown) > pi)
@test !(Float32(pi,RoundUp) < pi)

# issue #6365
for T in (Float32, Float64)
for i = 9007199254740992:9007199254740996
@test T(i) == T(BigFloat(i))
@test T(-i) == T(BigFloat(-i))
for r in (RoundNearest,RoundUp,RoundDown,RoundToZero)
@test T(i,r) == T(BigFloat(i),r)
@test T(-i,r) == T(BigFloat(-i),r)
end
end
end

@test prevfloat(big(pi)) < pi
@test nextfloat(big(pi)) > pi
@test !(prevfloat(big(pi)) > pi)
Expand Down

0 comments on commit 288ea08

Please sign in to comment.