My default Float type is Float64, however, I want to change that to Float32 as they are faster on my machine. I can set a global constant like const Float = Float32, but that forces me to use Float32 constructor everywhere. I wonder if there were a way to set the default float in a local environment.
You can use the package ChangePrecision.jl to change the precision of numeric literals in a block of code:
julia> using ChangePrecision
julia> @changeprecision Float32 begin
x = 7.3
y = 1/3
z = rand() .+ ones(3,4)
end
3×4 Matrix{Float32}:
1.20411 1.20411 1.20411 1.20411
1.20411 1.20411 1.20411 1.20411
1.20411 1.20411 1.20411 1.20411
julia> typeof.((x, y, z))
(Float32, Float32, Matrix{Float32})
An alternative to ChangePrecision are the SafeREPL and SwapLiterals packages:
julia> using SwapLiterals
julia> @swapliterals Float64 => Float32 begin
@show typeof(1.0)
1.0 + 2.0
end
typeof(1.0f0) = Float32
3.0f0
SafeREPL uses SwapLiterals to change the interpretation of literals at the REPL:
julia> using SafeREPL
julia> swapliterals!(Float64 => Float32)
julia> 1.0, typeof(1.0)
(1.0f0, Float32)
But unlike ChangePrecision, these packages don't change how rand and other functions work, e.g.
julia> @swapliterals Float64 => Float32 begin
x = 7.3
y = 1/3
z = rand() .+ ones(3,4)
typeof.((x, y, z))
end
(Float32, Float64, Matrix{Float64})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With