Search code examples
juliaarbitrary-precisionmultiprecision

In Julia: BigFloat RoundFromZero Seems Strange


In the Julia 1.0.0 REPL I get the following behavior. The first line is an example from the documentation https://docs.julialang.org/en/v1/base/math/#Base.Rounding.RoundFromZero

julia> BigFloat("1.0000000000000001", 5, RoundFromZero)
1.06

The meaning of the 5 in the above example is not clear to me. For example,

julia> BigFloat("1.01", 5, RoundFromZero)
1.06

It would seem that the two numbers being rounded should round to different outputs in the REPL. What am I missing?


Solution

  • The value is rounded from zero with 5 bits precision and in both cases this is the same value equal to 1.0625. You can check it using e.g.:

    julia> Float64(BigFloat("1.01", 5, RoundFromZero))
    1.0625
    

    or

    julia> big(0)+BigFloat("1.01", 5, RoundFromZero)
    1.0625
    

    or (this is hacking and should not be done):

    julia> x = BigFloat("1.01", 5, RoundFromZero)
    1.06
    
    julia> x.prec = 10
    10
    
    julia> x
    1.0625
    

    or

    julia> Base.MPFR._string(x, 10)
    "1.0625"
    

    Now the reason why 1.06 is printed is that Julia rounds the output (and this is a default rounding from MPFR external library in this case).