Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix conversion Irrational => Rational #16527

Merged
merged 1 commit into from
Jun 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Fix conversion Irrational => Rational
Fixes #16513. Changes generated macro to pure macro, so as to avoid breaking in future compiler changes.
  • Loading branch information
simonbyrne committed Jun 26, 2016
commit b1164b06522ca30d40aca2639a2579da76784b54
24 changes: 20 additions & 4 deletions base/irrationals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,27 @@ promote_rule{s,T<:Number}(::Type{Irrational{s}}, ::Type{T}) = promote_type(Float
convert(::Type{AbstractFloat}, x::Irrational) = Float64(x)
convert(::Type{Float16}, x::Irrational) = Float16(Float32(x))
convert{T<:Real}(::Type{Complex{T}}, x::Irrational) = convert(Complex{T}, convert(T,x))
convert{T<:Integer}(::Type{Rational{T}}, x::Irrational) = convert(Rational{T}, Float64(x))

@generated function (t::Type{T}){T<:Union{Float32,Float64},s}(c::Irrational{s},r::RoundingMode)
f = T(big(c()),r())
:($f)
@pure function convert{T<:Integer}(::Type{Rational{T}}, x::Irrational)
o = precision(BigFloat)
p = 256
while true
setprecision(BigFloat, p)
bx = BigFloat(x)
r = rationalize(T, bx, tol=0)
if abs(BigFloat(r) - bx) > eps(bx)
setprecision(BigFloat, o)
return r
end
p += 32
end
end
convert(::Type{Rational{BigInt}}, x::Irrational) = throw(ArgumentError("Cannot convert an Irrational to a Rational{BigInt}: use rationalize(Rational{BigInt}, x) instead"))

@pure function (t::Type{T}){T<:Union{Float32,Float64}}(x::Irrational, r::RoundingMode)
setprecision(BigFloat, 256) do
T(BigFloat(x), r)
end
end

=={s}(::Irrational{s}, ::Irrational{s}) = true
Expand Down
6 changes: 6 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2082,6 +2082,12 @@ for f in (trunc, round, floor, ceil)

@test isa(convert(Float64, big(1)//2), Float64)

# issue 16513
@test convert(Rational{Int32}, pi) == 1068966896 // 340262731
@test convert(Rational{Int64}, pi) == 2646693125139304345 // 842468587426513207
@test convert(Rational{Int128}, pi) == 60728338969805745700507212595448411044 // 19330430665609526556707216376512714945
@test_throws ArgumentError convert(Rational{BigInt}, pi)

# issue 5935
@test rationalize(Int8, nextfloat(0.1)) == 1//10
@test rationalize(Int64, nextfloat(0.1)) == 300239975158034//3002399751580339
Expand Down