JuliaMath / FixedPointNumbers.jl

fixed point types for julia
Other
80 stars 33 forks source link

support converting between different fixed-point representations #97

Open ssfrr opened 6 years ago

ssfrr commented 6 years ago

If I have a 24-bit fixed-point number x I might represent it as a Fixed{Int32, 23}. If I later wanted to widen it to a 32-bit number to get extra precision, I might try convert(Fixed{Int32, 31}, x, but that doesn't currently have a method. We could implement it just as a left shift.

I'm not sure what the best overflow checking behavior would be - in this case we'd worry about any values over 1 that would get lost. For a right-shift we'd get extra headroom but lose precision. Currently the float-to-fixed behavior is to throw an InexactError on an overflowing conversion but not when losing precision, so we could match that behavior and only need to check on left-shifts.

ssfrr commented 6 years ago

hah, I was just checking to see if there was an issue filed for this and it turns out I already filed one.

Does this seem like a good idea in general? I could probably put together a PR.

My general thought process is that if we suppose convert(::Type{Fixed}, x::FloatingPoint) it would make sense by analogy to support convert(::Type{Fixed}, x::Fixed}) which tries to represent the same value with the different representation.

timholy commented 6 years ago

Yes, having such conversion methods would be great. Do keep in mind the distinction between Fixed and Normed, what you describe may only be applicable to Fixed. It would be fine to only implement the methods for that case.