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.
2 Answers
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})
Float32
is normally faster on most computers, as far as I know. And if you want that extra speed you use an explicit constructor, or literal syntax, such as4.2f0
instead of4.2
, and1.3f-6
instead of1.3e-6
.