Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating average of two values, minimizing errors

I am doing some floating point calculations and the results are not as accurate as I want them to be.

This is the algorithm:

...
center = (max_x + min_x) / 2
distance = old_x - center
new_x = center + (distance * factor)

return new_x

min_x, max_x, and old_x are all floats. I believe that the greatest error is introduced when I'm taking the average of the max and the min, and then the error is multiplied by the factor (which can be a float).

How can I minimize the error due to FP computation so that new_x is as precise as it can be?

like image 409
MxLDevs Avatar asked Jun 24 '11 17:06

MxLDevs


People also ask

Does averaging reduce error?

The more measurements you average, the smaller your error in the mean. The error in the mean decreases as the square root of one over the number of measurements. Thus, to decrease the error of your measured values by a factor of 2, you must average 4 measurements.

What type of error does averaging reduce?

Random error can be reduced by: Using an average measurement from a set of measurements, or. Increasing sample size.


3 Answers

If old_x and center are close then you're losing precision.

It's called Loss of significance

You could change the calculation so the subtraction happenS in the end:

center = (max_x + min_x) / 2
new_x = (center + (old_x * factor)) - (center * factor)
like image 198
Yochai Timmer Avatar answered Sep 19 '22 03:09

Yochai Timmer


Depending on your language, there is probably a fixed/arbitrary precision numeric type you can use such as decimal in python or BigDecimal in Java.

like image 35
limscoder Avatar answered Sep 21 '22 03:09

limscoder


This eliminates at least one source of error from your original algorithm:

# Adding min and max can produce a value of larger magnitude, losing some low-order bits
center = min_x + (max_x - min_x)/2
distance = old_x - center
new_x = center + (distance * factor)

return new_x

If you have more knowledge of the relationship between old_x, min_x andmax_x, you can probably do better than this.

like image 29
Phil Miller Avatar answered Sep 21 '22 03:09

Phil Miller