Way to enforce `BigFloat` math by default

julia> big(pi)/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099

julia> big(pi/2)
1.5707963267948965579989817342720925807952880859375

That is quite an easy mistake to make. Is there a way to do something like set the default numeric type for literals to BigFloat, to help avoid silently wrong math?

Overriding the builtin values with something like pi = big(pi) would also help, but unfortunately this is not allowed.

1 Like

I bet it would be possible to write a JET analyzer type that checks for floats.

That’s the purpose of the SwapLiterals.jl and SafeREPL.jl packages. At the REPL:

julia> using SafeREPL

julia> swapliterals!(Float64 => :BigFloat)  # `BigFloat` function is applied to Float64 literals

julia> 1.2 # identical to `BigFloat(1.2)`
1.1999999999999999555910790149937383830547332763671875

julia> big"1.2"
1.200000000000000000000000000000000000000000000000000000000000000000000000000007

julia> swapliterals!(Float64 => "@big_str")  # apply `@big_str` macro to stringified Float64 literals
1.200000000000000000000000000000000000000000000000000000000000000000000000000007

julia> pi/2 # no Float64 literals, so vanilla julia
1.5707963267948966

julia> pi/2.0
1.570796326794896619231321691639751442098584699687552910487472296153908203143099

julia> swapliterals!(Float64 => :BigFloat, Int => :BigInt) # convert Int literals into BigInt

julia> pi/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099

To swap literals in code (not in REPL) :

julia> using SwapLiterals; @swapliterals Float64 => "@big_str" 1.2
1.200000000000000000000000000000000000000000000000000000000000000000000000000007
4 Likes

that’s not “swap”, that’s "assign":laughing:

3 Likes

Just do pi = BigFloat(MathConstants.pi).

2 Likes

You may be interested in SafeREPL.jl:

julia> using SafeREPL

julia> π
π = 3.1415926535897...

julia> π/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099

julia> BigFloat(π)/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099
2 Likes

Or “replace”.

1 Like