How to Precisely Spread Numbers?
โ Rust ๐ 2025-06-21 ๐ค surdeus ๐๏ธ 17I 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
๐ท๏ธ rust_feed