Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a set of numbers while ensuring the total adds to 1

I'm looking for a way to round a set of numbers to the nearest rational number while still preserving the total of the set.

I want to distribute the total value of '1' amongst a variable number of fields without allowing irrational numbers.

So say I want to distribute the total across three fields. I don't want each value to be 0.33333333333333333333'. I would prefer 0.33, 0.33 & 0.34.

I would like to implement this using Jquery/javascript. I have a form where fields are added dynamically. By default the total is evenly distributed amongst each field, however my problem is further complicated because often the value will not be shared equally amongst all fields. Some values might be more heavily weighted. So if I were to change one of the three values to 0.5, the other two values would be adjusted to 0.25.

Can anyone help with a suitable algorithm?

like image 507
poleposters Avatar asked Dec 10 '22 13:12

poleposters


1 Answers

Not perfect, but easy to write:

  1. Round every number to the nearest acceptable value. As you go, keep track of which number you rounded upward by the largest amount and which number you rounded downward by the largest amount.
  2. Sum the numbers up.
  3. Subtract that sum from 1.
  4. If the difference is negative, add it to the number you rounded upward the most. If the difference is positive, add it to the number you rounded downward the most.
like image 185
AlcubierreDrive Avatar answered May 23 '23 14:05

AlcubierreDrive