How to indicate in which direction to round off the average of two floats that differ in LSB from their significance?

I am working on a Nelder-Mead optimization routine in C that involves averaging two floats. In rare (but quite reproducible) circumstances, two floats, say xand y, differ only in the least significant bit of their significance. When the average is fulfilled, rounding errors imply that the result will be either xor y.

I would like to point out that rounding should always be in the second float. That is, I cannot simply indicate that rounding should be at zero or infinity, because I do not know in advance whether there will be xmore than that y.

(How can i do this?

+5
source share
2 answers

I do not think there is a hardware rounding mode for this. You have to write your own function, then

double average(double x, double y) {
    double a = 0.5*(x+y);
    return (a == x) ? y : a;
}
+2
source

You can find out a special case and select the value you want to return.

The values โ€‹โ€‹of interest are as follows:

  • When values โ€‹โ€‹have the same sign and exponent and only differ in the mantissa.

  • When the values โ€‹โ€‹have the same sign, the exponents differ by one, and a unit with a large exponent has a mantissa of 0, and the other mantissa is filled with units.

In fact, if you use IEEE-754 numbers (which you probably are), you can run both tests at once (after checking things like Zero, Inf and Nan):

if (   repr1 + 1 == repr2
    || repr2 + 1 == repr1)
  ....

, , - , .

, , . , , , , , . , .

0

All Articles