views:

1071

answers:

9

Let's say I have an array of floating point numbers, in sorted (let's say ascending) order, whose sum is known to be an integer N. I want to "round" these numbers to integers while leaving their sum unchanged. In other words, I'm looking for an algorithm that converts the array of floating-point numbers (call it fn) to an array of integers (call it in) such that:

  1. the two arrays have the same length
  2. the sum of the array of integers is N
  3. the difference between each floating-point number fn[i] and its corresponding integer in[i] is less than 1 (or equal to 1 if you really must)
  4. given that the floats are in sorted order (fn[i] <= fn[i+1]), the integers will also be in sorted order (in[i] <= in[i+1])

Given that those four conditions are satisfied, an algorithm that minimizes the rounding variance (sum((in[i] - fn[i])^2)) is preferable, but it's not a big deal.

Examples:

    [0.02, 0.03, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14]
        => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
    [0.1, 0.3, 0.4, 0.4, 0.8] => [0, 0, 0, 1, 1]
    [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
        => [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
    [0.4, 0.4, 0.4, 0.4, 9.2, 9.2]
        => [0, 0, 1, 1, 9, 9] is preferable
        => [0, 0, 0, 0, 10, 10] is acceptable
    [0.5, 0.5, 11]
        => [0, 1, 11] is fine
        => [0, 0, 12] is technically not allowed but I'd take it in a pinch

EDIT: Wow, I wasn't expecting such a strong response overnight! I clarified the conditions above. To answer some excellent questions raised in the comments:

  • Repeated elements are allowed in both arrays (although I would also be interested to hear about algorithms that work only if the array of floats does not include repeats)
  • There is no single correct answer - for a given input array of floats, there are generally multiple arrays of ints that satisfy the four conditions.
  • The application I had in mind was - and this is kind of odd - distributing points to the top finishers in a game of MarioKart ;-) Never actually played the game myself, but while watching someone else I noticed that there were 24 points distributed among the top 4 finishers, and I wondered how it might be possible to distribute the points according to finishing time (so if someone finishes with a large lead they get a larger share of the points). The game tracks point totals as integers, hence the need for this kind of rounding.
A: 

Can you try something like this?

in [i] = fn [i] - int (fn [i]);
fn_res [i] = fn [i] - in [i];

fn_res → is the resultant fraction. (I thought this was basic ...), Are we missing something?

Alphaneo
+12  A: 

One really easy way is to take all the fractional parts and sum them up. That number by the definition of your problem must be a whole number. Distribute that whole number evenly starting with the largest of your numbers. Then give one to the second largest number... etc. until you run out of things to distribute.

Note this is pseudocode... and may be off by one in an index... its late and I am sleepy.

float accumulator = 0;

for (i = 0; i < num_elements; i++)  /* assumes 0 based array */
{
   accumulator += (fn[i] - floor(fn[i])); 
   fn[i] =  (fn[i] - floor(fn[i]);
}

i = num_elements;

while ((accumulator > 0) && (i>=0))
{
    fn[i-1] += 1;   /* assumes 0 based array */
    accumulator -= 1;
    i--;
}

Update: There are other methods of distributing the accumulated values based on how much truncation was performed on each value. This would require keeping a seperate list called loss[i] = fn[i] - floor(fn[i]). You can then repeat over the fn[i] list and give 1 to the greatest loss item repeatedly (setting the loss[i] to 0 afterwards). Its complicated but I guess it works.

ojblass
... and skipping those numbers who, when incremented would become unsorted.
MSalters
hmmm i think by going from the largest down you would by definition keep the sort order... am I missing something? example?
ojblass
If you are starting with the largest, second largest, etc - then how would they become unsorted?
Marc Gravell
Nice answer - I like this ;-p
Marc Gravell
What about [ 0.4, 0.4, 0.4, 0.4, 9.2, 9.2 ]? I believe the algorithm should provide an answer of [ 0, 0, 1, 1, 9, 9 ] here.
Mikko Rantanen
I think my algorithm would make it [0, 0, 0, 0, 10, 10]
ojblass
@ojblass - seconded (just had to think for a second ;-p) - which is a perfectly legal answer to the problem.
Marc Gravell
I think it somewhat satisfies the conditions but no telling until clarification is provided.
ojblass
Actually I think even the reference [1.3, 1.7, 1.9, 2.2, 2.8, 3.1] => [1, 2, 2, 2, 3, 3] fails? First pass you get fn[i] of [1, 1, 1, 2, 2, 3] as you were taking a floor of the numbers. Next you'll increment the largest numbers giving you [1, 1, 1, 3, 3, 4].
Mikko Rantanen
Well, it certainly satisfied the 4 bullet points...
Marc Gravell
@Mikko - the [1,2,2,3,3] is just *a* feasible solution. There are often many feasible solutions to such problems. [1,1,1,3,3,4] is just as feasible.
Marc Gravell
[1, 1, 1, 3, 3, 4] rounds 1.9 to 1 and 2.2 to 3. I believe the idea was to round as accurately as possible.
Mikko Rantanen
The problem is that the there are multiple rounding strategies yielding different answers...
ojblass
I am beginning to like James's solution
ojblass
@Mikko - it doesn't say that in the question...
Marc Gravell
Well, I'd say the references are part of the question. *Goes add a TDD tag* ;) But my point is more or less: As there is a way to minimize the roundoff error, why not do so?
Mikko Rantanen
And and and! (Yes.. I admit I just can't stop..) Given [ 0.5, 0.5, 11 ] this will be rounded to [ 0, 0, 12 ] in which case 12-11 is 1 while the original question required that the difference is less than 1. And I hope you're not taking this personally. I'm just so very surprised at the amount of answers which just round the highest numbers, all of which have the same problems.
Mikko Rantanen
Nothing is taken personally...
ojblass
+10  A: 

One option you could try is "cascade rounding".

For this algorithm you keep tow running totals one of you floating point numbers so far, and one of the integers so far. To get the next integer you add the next fp number to your running total, round the running total, then subtract the intger running total from the rounded running total:-

number  running total   integer integer running total
   1.3       1.3          1           1
   1.7       3.0          2           3
   1.9       4.9          2           5
   2.2       8.1          3           8
   2.8      10.9          3          11
   3.1      14.0          3          14
James Anderson
I think this would have more accurate rounding than mine.
ojblass
I think this one invalidates the "If fn is sorted -> in is sorted" rule without an extra sort step. [0.4, 0.2, 0.4, 0.4, 0.2, 0.4, ...] will round to [0, 1, 0, 0, 1, 0, ... ].
Mikko Rantanen
@mikko: is [0.4, 0.2, 0.4, 0.4, 0.2, 0.4, ...] really sorted?
artificialidiot
Er. Good point. I mixed two counter examples. The original was [ 0.3, 0.3, 0.3, 0.3, ... ] which will become something like [0, 1, 0, 0, ...]. The [0.4, 0.2, 0.4, 0.2, ..] example should have been [0.4, 1.2, 2.4] which demonstrates less than optimal roundoff error. as the first 0.4 rounds off to 0 (error 0.4), 1.2 to 2 (error sum 1.2) and 2.4 again to 2 (error sum 2.8) while the optimal would round 0.4 or 2.4 up (error 0.6), the remaining .4 down (error sum 1.0 and 1.2 down (error sum 1.2).
Mikko Rantanen
Mikko: good point about the sorted rule.Also be aware that this looks really odd when there are lots of values close to 0 and 1 .
James Anderson
A: 

Well, 4 is the pain point. Otherwise you could do things like "usually round down and accumulate leftover; round up when accumulator >= 1". (edit: actually, that might still be OK as long as you swapped their position?)

There might be a way to do it with linear programming? (that's maths "programming", not computer programming - you'd need some maths to find the feasible solution, although you could probably skip the usual "optimisation" part).

As an example of the linear programming - with the example [1.3, 1.7, 1.9, 2.2, 2.8, 3.1] you could have the rules:

1 <= i < 2
1 <= j < 2
1 <= k < 2
2 <= l < 3
3 <= m < 4
i <= j <= k <= l <= m
i + j + k + l + m = 13

Then apply some linear/matrix algebra ;-p Hint: there are products to do the above based on things like the "Simplex" algorithm. Common university fodder, too (I wrote one at uni for my final project).

Marc Gravell
A: 

Essentially what you'd do is distribute the leftovers after rounding to the most likely candidates.

  1. Round the floats as you normally would, but keep track of the delta from rounding and associated index into fn and in.
  2. Sort the second array by delta.
  3. While sum(in) < N, work forwards from the largest negative delta, incrementing the rounded value (making sure you still satisfy rule #3).
  4. Or, while sum(in) > N, work backwards from the largest positive delta, decrementing the rounded value (making sure you still satisfy rule #3).

Example:

[0.02, 0.03, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14] N=1

1. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] sum=0
and [[-0.02, 0], [-0.03, 1], [-0.05, 2], [-0.06, 3], [-0.07, 4], [-0.08, 5], 
     [-0.09, 6], [-0.1, 7], [-0.11, 8], [-0.12, 9], [-0.13, 10], [-0.14, 11]]

2. sorting will reverse the array

3. working from the largest negative remainder, you get [-0.14, 11].
Increment `in[11]` and you get [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] sum=1 
Done.
lc
And buy a flux capacitor while you are at it.
ojblass
Yeah, definitely agreed it's a bit of a mess, but it ought to work.
lc
This should work. Though you could make it a bit clearer by always rounding to one direction (such as down) and then working from the largest abs(delta) and compensating.
Mikko Rantanen
A: 

Here is one algorithm which should accomplish the task. The main difference to other algorithms is that this one rounds the numbers in correct order always. Minimizing roundoff error.

The language is some pseudo language which probably derived from JavaScript or Lua. Should explain the point. Note the one based indexing (which is nicer with x to y for loops. :p)

// Temp array with same length as fn.
tempArr = Array(fn.length)

// Calculate the expected sum.
arraySum = sum(fn)

lowerSum = 0
-- Populate temp array.
for i = 1 to fn.lengthf
    tempArr[i] = { result: floor(fn[i]),              // Lower bound
                   difference: fn[i] - floor(fn[i]),  // Roundoff error
                   index: i }                         // Original index

    // Calculate the lower sum
    lowerSum = lowerSum + tempArr[i] + lowerBound
end for

// Sort the temp array on the roundoff error
sort(tempArr, "difference")

// Now arraySum - lowerSum gives us the difference between sums of these
// arrays. tempArr is ordered in such a way that the numbers closest to the
// next one are at the top.
difference = arraySum - lowerSum

// Add 1 to those most likely to round up to the next number so that
// the difference is nullified.
for i = (tempArr.length - difference + 1) to tempArr.length
    tempArr.result = tempArr.result + 1
end for

// Optionally sort the array based on the original index.
array(sort, "index")
Mikko Rantanen
A: 

Make the summed diffs are to be under 1, and check to be sorted. some like,

ex) while(i < sizeof(fn) / sizeof(float)) {

res += fn[i] - floor(fn[i]);

if (res >= 1) {

res--;

in[i] = ceil(fn[i]);

}

else

in[i] = floor(fn[i]);

if (in[i-1] > in[i])

swap(in[i-1], in[i++]);

}

(it's paper code, so i didn't check the validity.)

A: 

The problem, as I see it, is that the sorting algorithm is not specified. Or more like - whether it's a stable sort or not.

Consider the following array of floats:

[ 0.2 0.2 0.2 0.2 0.2 ]

The sum is 1. The integer array then should be:

[ 0 0 0 0 1 ]

However, if the sorting algorithm isn't stable, it could sort the "1" somewhere else in the array...

Vilx-
In that sense it should be a stable sort, then. [0 0 0 0 1] would be a desired result. The intent of rule 4 is to say that [0 0 0 1 0] would be unacceptable. (Good point though)
David Zaslavsky
+1  A: 

How about:

a) start: array is [0.1, 0.2, 0.4, 0.5, 0.8], N=3, presuming it's sorted
b) round them all the usual way: array is [0 0 0 1 1]
c) get the sum of the new array and subtract it from N to get the remainder.
d) while remainder>0, iterate through elements, going from the last one
   - check if the new value would break rule 3.
   - if not, add 1
e) in case that remainder<0, iterate from first one to the last one
   - check if the new value would break rule 3.
   - if not, subtract 1
Groo
One could determine the top n values, (where n is the difference between the summed floats and the summed integers) this would remove the need to sort the array. Using a heap getting the top n values can be made a O(n) operation.
Georg