How to Precisely Spread Numbers?

โš“ Rust    ๐Ÿ“… 2025-06-21    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 7      

surdeus

Warning

This post was published 52 days ago. The information described in this article may have changed.

I want to spread a bunch of integers of primitive type T to a different range, typically T::MIN..=T::MAX. They might be percentages, i.e. add up to 100. Mathematically adjusting their sizes is easy: Say T is u8, then in this case let new = old * 255 / 100. Except the multiplication will overflow, whereas let new = old / 100 * 255 will first truncate to zero.

Obviously let new = old * 2.55 would be the solution, but it is not possible to mix types. Also I canโ€™t generally convert old to float, because, even if we already had f128, floats always have less precision than an equal-sized integer.

I guess Iโ€™d need mul_rem<F: {float}>(self, factor: F) -> (Self, F) which would return the floor and the truncated fractional part of the product. (The sum of the floors will often fall short, so Iโ€™d then have to adjust: add 1 to some of those with the highest fractional parts.)

I want to do this in const, but Iโ€™m beginning to wonder whether this is at all generally possible (i.e. not only on numbers small enough to losslessly fit into float.)

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ rust_feed