Search code examples
javascriptroundingfractions

Summing and rounding fractions multiplied by number to equal number?


In JavaScript, Given (x) number of fractions like this:

0.3
0.3
0.2
0.1
0.1

(That sum to 1)

How can I make sure that when I multiply these by a number (n), say 1000, and round the results to integers, the sum of these integers will equal (n)?


Solution

  • Use the Largest Remainder Method:

    Step 1: Multiply the numbers by n (in this case, let's use an n that doesn't immediately work out so nicely to demonstrate that the LRM still works; I choose 737), and separate the whole and fractional parts.

    0.3 * 737 = 221 + 0.1
    0.3 * 737 = 221 + 0.1
    0.2 * 737 = 147 + 0.4
    0.1 * 737 = 73 + 0.7
    0.1 * 737 = 73 + 0.7
    

    Step 2: Sum up the whole number parts

    221 + 221 + 147 + 73 + 73 = 735
    

    Step 3: Sort the remainders from highest to lowest

    High to low: 0.7, 0.7, 0.4, 0.1, 0.1
    

    Step 4: Add 1 to the whole number components with the associated largest remainders until the sum equals n.

    In our case, we are 2 away from the target sum (737), and 0.7 is the largest remainder, which occurs twice. 0.7 is associated with 0.1, so add 1 to 0.1's whole number.

    Your final list is:

    221
    221
    147
    74
    74