Skip to content

Incorrect rounding when converting rational to bigfloat #58432

@lucaferranti

Description

@lucaferranti
julia> versioninfo()
Julia Version 1.12.0-beta1
Commit c175ace780d (2025-04-02 11:19 UTC)
Build Info:
  Official https://julialang.org release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 12 × 12th Gen Intel(R) Core(TM) i7-1255U
  WORD_SIZE: 64
  LLVM: libLLVM-18.1.7 (ORCJIT, alderlake)
  GC: Built with stock GC
Threads: 1 default, 1 interactive, 1 GC (on 12 virtual cores)
Environment:
  JULIA_EDITOR = hx

julia> a = 1 // (big(2)^300 + 1)
1//2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397377

julia> a_up = BigFloat(a, RoundUp)
4.909093465297726553095771954986275642975215512499449565111549117187105254721673e-91

julia> a_down = BigFloat(a, RoundDown)
4.909093465297726553095771954986275642975215512499449565111549117187105254721716e-91

julia> a_down > a_up
true

here the rounded down version is strictly bigger than the rounded up version. Implementation seems to be

function BigFloat(x::Rational, r::MPFRRoundingMode=rounding_raw(BigFloat); precision::Integer=_precision_with_base_2(BigFloat))
    setprecision(BigFloat, precision) do
        setrounding_raw(BigFloat, r) do
            BigFloat(numerator(x))::BigFloat / BigFloat(denominator(x))::BigFloat
        end
    end
end

I think the problem is that here BigFloat(denominator(x)) is not exact (with default 256 bits precision) and it's rounded up when computing a_up, but to correctly round up the ratio, the denominator should be rounded down.

Metadata

Metadata

Assignees

Labels

bignumsBigInt and BigFloatrationalsThe Rational type and values thereof

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions