I’ve been reading a lot of posts about rounding off numbers, but I couldn’t manage to do what I want :
I have got a list of positive floats.
The unsigned integer roundOffStep to use is user-defined. I have no control other it.
I want to be able to do the most accurate rounding while preserving the sum of those numbers, or at least while keeping the new sum inferior to the original sum.
How would I do that ? I am terrible with algorithms, so this is way too tricky for me.
Thx.
EDIT : Adding a Test case :
FLOATS
29.20
18.25
14.60
8.76
2.19
sum = 73;
Let’s say roundOffStep = 5;
ROUNDED FLOATS
30
15
15
10
0
sum = 70 < 73 OK
roundOffStepnormally.rounded_number - original_number. Sort this list of differences in decreasing order so that you can find the numbers with the largest difference.rounded_number - original_number, and subtractroundOffStepfrom that number.This process should ensure that the rounded numbers are as close as possible to the originals, without going over the original sum.
Example, with
roundOffStep = 5:The sum is too large, so we pick the number giving the largest difference (18.25 which was rounded to 20) and subtract 5 to give 15. Now the sum is 70, so we’re done.