On Sep 18, 11:20 am, Spoon <root@localhostwrote:

I don't understand how the lrint() function works.

long lrint(double x);

Just a technicality, but this function doesn't exist (yet) in

C++; it's part of C99. (On the other hand, it will be part of

the next C++ standard, and I would expect most implementations

of C++ to support it already.)

The function returns the nearest long integer to x, consistent with the

current rounding mode. It raises an invalid floating-point exception if

the magnitude of the rounded value is too large to represent. And it

raises an inexact floating-point exception if the return value does not

equal x.

The output of the following program does not make sense to me.

#include <cstdio>

#include <cmath>

int main()

{

for (int i=-10; i < 10; ++i)

{

double x = i + 0.5;

printf("lrint(%+f)=%ld\n", x, lrint(x));

}

return 0;

}

$ g++ -std=c++98 -Wall -Wextra -O2 -march=pentium3 foo.cxx -lm

$ ./a.out

lrint(-9.500000)=-10

lrint(-8.500000)=-8

lrint(-7.500000)=-8

lrint(-6.500000)=-6

lrint(-5.500000)=-6

lrint(-4.500000)=-4

lrint(-3.500000)=-4

lrint(-2.500000)=-2

lrint(-1.500000)=-2

lrint(-0.500000)=0

lrint(+0.500000)=0

lrint(+1.500000)=2

lrint(+2.500000)=2

lrint(+3.500000)=4

lrint(+4.500000)=4

lrint(+5.500000)=6

lrint(+6.500000)=6

lrint(+7.500000)=8

lrint(+8.500000)=8

lrint(+9.500000)=10

How could 1.5 AND 2.5 be rounded to 2 in the same rounding mode?

Those are the rules for IEEE round to nearest mode. In the case

of .5, it rounds to even. The reason for this is so that there

will be no overall bias in the rounding; if you use the

"standard" rounding, with 0.5 rounding up, you introduce a bias

towards higher values. (If you add the rounded positive values

in your example, the results will be very close to the results

of adding the unrounded values if IEEE round to nearest is used;

with the classical commercial rounding, they would be

significantly greater.)

Note that you cannot always use this rounding in commercial

software; most countries have laws concerning what is good

bookkeeping practices, and impose very specific rules of

rounding, including the fact that 0.5 cents always rounds away

from 0. (Of course, since the rules are based on decimal

values, you generally can't use double directly anyway.)

--

James Kanze (GABI Software) email:ja*********@gmail.com

Conseils en informatique orientée objet/

Beratung in objektorientierter Datenverarbeitung

9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34