How can I solve c++ std::rintf issue in gcc

114 views Asked by At

I don't understand, why std::rintf returns the following results (g++ 7.3.0):

cout << rintf(14.5f) << endl;            
cout << rintf(15.5f) << endl;             
cout << rintf(16.5f) << endl;

result:

14
16
16

The source numbers can be stored in float precisely, so this shouldn't be a computation issue.

I checked the source and it uses __builtin_rintf.

I can write my own function, of course, but this issue disturbs me.

1

There are 1 answers

0
Pete Becker On

This is “banker’s rounding”, also known as “round to even”. The issue is that a value of x.5 is exactly half way between x and x+1. There are a bunch of possible ways to handle rounding values like that. Round to even rounds to an even number, so 14.5 becomes 14, 15.5 becomes 16, and 16.5 becomes 16. I’ve heard that over a bunch of calculations this reduces cumulative rounding errors.

Other possibilities include round toward 0: 14.5 becomes 14 and -14.5 becomes -14; round toward negative infinity (round down): 14.5 becomes 14 and -14.5 becomes -15; round away from 0: 14.5 becomes 15 and -14.5 becomes -15; round toward positive infinity (round up): 14.5 becomes 15 and -14.5 becomes -14.

There is usually a way to select the rounding mode, but standard C++ doesn’t address rounding.