[ANN] SuffixConversion.jl - make it easier to write generic code with numerical literals

I’m announcing SuffixConversion.jl, which aims to make it easier to write generic code involving numeric literals without unintentional type promotion. An example:

using SuffixConversion

function addhalf(x)
    @suffix FT = typeof(x)
    return x + 0.5_FT
end    

Thoughts/comments welcome!

3 Likes

It would be helpful to show the normal way of doing the conversion without syntactic sugar so we can have something familiar to compare to.

Note that this still seems to lose precision in many cases if the starting number is not exactly represented as a Float64 literal, e.g.:

julia> using DecFP

julia> @suffix Dec128
SuffixConversion.SuffixConverter{Dec128}()

julia> 0.1_Dec128
0.1000000000000000055511151231257827

(You work around this for BigFloat only by converting to string first. You could do this for all types, of course, but then performance would really suffer.)

1 Like

See the bottom of the README?

1 Like

FT(0.5). If you have a rational number that is not exactly representable by a Float64 literal, however, you’re better off using a rational expression, e.g. FT(1//10) rather than FT(0.1). (See my post above.)

1 Like

in this case it’s just

struct Converter{T} end
Base.:(*)(x, ::Converter{T}) where {T} = convert(T, x)
function addhalf(x)
    _FT = Converter{typeof(x)}()
   return x + 0.5_FT
end
2 Likes

Good point, I can add that to the README.