Skip to content

rationalize(x::AbstractIrrational) - Excess use of precision that doesn't add accuracy #60772

@lvlte

Description

@lvlte
julia> r1 = rationalize(BigInt, pi)
45471447111470790535029367847216232831674172166049053744846518889742361808273//14474011154664524427946373126085988481658748083205070504932198000989141204992

julia> r1 == rationalize(BigInt, big(pi), tol=0)
true

julia> r2 = rationalize(BigInt, big(pi))                    # default tol = eps(big(pi))
256839923861488782607902790348837497679//81754686931803956266412424933874257924

julia> setprecision(BigFloat, 512)
512

julia> abs(big(pi) - r1)
1.09691744097935207674213062639569802105075823650868795117900571699214268851335408432758687152126862893780646098416714064893273395878360216160514794183137669e-77

julia> abs(big(pi) - r2)
8.68325468754537686640586102920198018597138664132865761850237938790771426269835867462688355683840647221791210774535376432503951918104705495036553946054924821e-78

It appears rationalize(x::AbstractIrrational) rationalizes big(pi) with tol=0 by default. Setting a tolerance lower than eps(big(pi))/2 will encode the roundoff error in the rational components, this will only increase the magnitude of the components without adding accuracy. Increasing the precision of BigFoat should be done instead, depending on the given tol.

Another issue is that the default tolerance is zero for AbstractIrrational, which doesn't really make sense.

function rationalize(::Type{T}, x::AbstractIrrational; tol::Real=0) where {T<:Integer}

In particular, shouldn't rationalize(BigInt, pi, tol=0) throw as Rational{BigInt}(pi) does ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions