Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify in which direction to round the average of two floats that differ by the LSB of their significand?

I'm working on a Nelder-Mead optimization routine in C that involves taking the average of two floats. In rare (but perfectly reproducible) circumstances, the two floats, say x and y, differ only by the least significant bit of their significand. When the average is taken, rounding errors imply that the result will be either x or y.

I'd like to specify that rounding should always be towards the second float. That is, I cannot simply specify that rounding should be towards zero, or infinity, because I do not know in advance whether x will be larger than y.

(How) can I do that?

like image 291
lindelof Avatar asked Nov 05 '22 07:11

lindelof


1 Answers

I don't think there's a hardware rounding mode for that. 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;
}
like image 117
Daniel Fischer Avatar answered Nov 09 '22 08:11

Daniel Fischer