-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Description
It is nice to use rationals for constants like 2//3
that are supposed to be precision-independent, in a context like f(x) = x * (2//3)
, but they still impose a performance cost because converting them to Float32
or Float64
involves a runtime division. Can this be made to happen at compile-time?
@pure (::Type{T})(x::Rational{<:BitInteger}) where T<:Union{Float16,Float32,Float64} = T(x.num/x.den)
apparently doesn't work — @code_native f(2.3)
still shows a runtime division.
This feature was requested in #14324, which was "fixed" in #24362 by @vtjnash — does that mean that there is supposed to be an annotation that enables constant-folding here? (If not, why was #14324 closed?)
In contrast, g(x) = x * (oftype(x,2) / oftype(x,3))
works (@code_native g(3.7)
shows that the constant 2/3 ≈ 0.6666666666666666 is constructed at compile time) but is obviously more cumbersome to write.