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
jar1
April 5, 2024, 5:37am
2
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
photor
April 5, 2024, 9:02am
4
that’s not “swap”, that’s "assign"
3 Likes
nsajko
April 5, 2024, 9:20am
5
Just do pi = BigFloat(MathConstants.pi)
.
2 Likes
mkitti
April 5, 2024, 6:28pm
6
You may be interested in SafeREPL.jl:
With Julia 1.5 around the corner, I’m happy to present SafeREPL , a little experimental package which by default interprets Int and Int128 REPL literals as BigInt, and Float64 literals as BigFloat:
julia> using SafeREPL
julia> factorial(40)
815915283247897734345611269596115894272000000000
julia> sqrt(2.0)
1.414213562373095048801688724209698078569671875376948073176679737990732478462102
julia> c = 299_792_458; c^3 # the cube of the speed of light can even be computed safely!
26944002417373989…
julia> using SafeREPL
julia> π
Ď€ = 3.1415926535897...
julia> π/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099
julia> BigFloat(Ď€)/2
1.570796326794896619231321691639751442098584699687552910487472296153908203143099
2 Likes