Skip to content

Commit b72a316

Browse files
committed
don't mutate globals when constructing Rational from AbstractIrrational
Relying on `ScopedValues`, set `BigFloat` precision without mutating the global default, while constructing `Rational` from `AbstractIrrational`. Also helps avoid reading the global defaults for the precision and rounding mode, together with JuliaLang#56095.
1 parent 0bedaae commit b72a316

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

base/irrationals.jl

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,20 +60,43 @@ AbstractFloat(x::AbstractIrrational) = Float64(x)::Float64
6060
Float16(x::AbstractIrrational) = Float16(Float32(x)::Float32)
6161
Complex{T}(x::AbstractIrrational) where {T<:Real} = Complex{T}(T(x))
6262

63-
function _irrational_to_rational(::Type{T}, x::AbstractIrrational) where T<:Integer
64-
o = precision(BigFloat)
63+
function _irrational_to_rational_at_current_precision(::Type{T}, x::AbstractIrrational) where {T <: Integer}
64+
bx = BigFloat(x)
65+
r = rationalize(T, bx, tol = 0)
66+
br = BigFloat(r, precision = precision(BigFloat) + 32)
67+
if eps(bx) < abs(br - bx)
68+
r
69+
else
70+
nothing # Error is too small, repeat with greater precision.
71+
end
72+
end
73+
function _irrational_to_rational_at_precision(::Type{T}, x::AbstractIrrational, p::Int) where {T <: Integer}
74+
f = let x = x
75+
() -> _irrational_to_rational_at_current_precision(T, x)
76+
end
77+
setprecision(f, BigFloat, p)
78+
end
79+
function _irrational_to_rational_at_current_rounding_mode(::Type{T}, x::AbstractIrrational) where {T <: Integer}
80+
if T <: BigInt
81+
_throw_argument_error_irrational_to_rational_bigint() # avoid infinite loop
82+
end
6583
p = 256
6684
while true
67-
setprecision(BigFloat, p)
68-
bx = BigFloat(x)
69-
r = rationalize(T, bx, tol=0)
70-
if abs(BigFloat(r) - bx) > eps(bx)
71-
setprecision(BigFloat, o)
85+
r = _irrational_to_rational_at_precision(T, x, p)
86+
if r isa Number
7287
return r
7388
end
7489
p += 32
7590
end
7691
end
92+
function _irrational_to_rational(
93+
::Type{T}, x::AbstractIrrational,
94+
) where {T <: Integer}
95+
f = let x = x
96+
() -> _irrational_to_rational_at_current_rounding_mode(T, x)
97+
end
98+
setrounding(f, BigFloat, RoundNearest)
99+
end
77100
Rational{T}(x::AbstractIrrational) where {T<:Integer} = _irrational_to_rational(T, x)
78101
_throw_argument_error_irrational_to_rational_bigint() = throw(ArgumentError("Cannot convert an AbstractIrrational to a Rational{BigInt}: use rationalize(BigInt, x) instead"))
79102
Rational{BigInt}(::AbstractIrrational) = _throw_argument_error_irrational_to_rational_bigint()

0 commit comments

Comments
 (0)