juliabigfloat

How to use setprecision in Julia?


I am trying to increment a code that uses the setprecision function, but every time I use an example, however simple, it always gives the same error.

when I do: x = big"1.23456789" setprecision(x, 20) I get the following error:

ERROR: LoadError: MethodError: no method matching setprecision(::BigFloat, ::Int64)
Closest candidates are:
  setprecision(::Type{BigFloat}, ::Integer; base) at mpfr.jl:840
  setprecision(::Function, ::Integer; base) at mpfr.jl:969
Stacktrace:
 [1] top-level scope


Solution

  • The setprecision function accepts a type, and globally sets the precision for all operations on this type (there is a variant that does this temporary, but let me focus on a simpler scenario). So what you should do is for example:

    julia> setprecision(BigFloat, 20) # low precision
    20
    
    julia> x = big"1.23456789"
    1.2345676
    
    julia> setprecision(BigFloat, 200) # higher precision
    200
    
    julia> x = big"1.23456789"
    1.2345678900000000000000000000000000000000000000000000000000004
    

    After setprecision all operations on BigFloat values will use the precision you set.

    Note that you should set precision first and only next perform some operation. See an example:

    julia> x = big"1.23456789"
    1.234567889999999999999999999999999999999999999999999999999999999999999999999998
    
    julia> setprecision(BigFloat, 20)
    20
    
    julia> x # still high precision because we created x before changing precision
    1.234567889999999999999999999999999999999999999999999999999999999999999999999998
    
    julia> x * 1 # the result of computation has lower precision since it is computed after calling setprecision
    1.2345676