user1697083
user1697083

Reputation:

Sorting float values for averages

I know generally why it would be advisable to sort a float at all in order to calculate the average of several values in array: you would risk adding together values that are farther apart gap-wise - and thus distort the overall value.

But why would the accuracy further increase if you decided to order them not in ascending order, but descending order? I've come across a few average formulations for floats and have noticed a preference to sort them in descending order and wondered why this is so?

Upvotes: 4

Views: 352

Answers (1)

user1196549
user1196549

Reputation:

Because of truncation errors.

Assume that your floating-point arithmetic just stores four significant digits.

7.000 + 0.0003 + 0.0003 + 0.0003 + 0.0003 yields 7.000, 7.000, 7.000, 7.000.

while

0.0003 + 0.0003 + 0.0003 + 0.0003 + 7.000 yields 0.0006, 0.0009, 0.0012, 7.001.

When you add a small number to a much bigger one, the last decimals get lost. When the numbers are balanced, this effect is lessened.

Upvotes: 3

Related Questions