2

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)?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dani
  • 4,880
  • 8
  • 55
  • 95

2 Answers2

3

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
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • 1
    Great answer and thanks for 1) Linking to the actual method so that I remember the term and 2) for giving the solution stepwise. – dani Dec 02 '11 at 22:46
0

You can't guarantee it if you multiply, round, and sum. Why don't you sum first, then multiply, then round?

dgundersen
  • 447
  • 3
  • 16