This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: linux i-86 problem with rounding (gcc-3.1.1 & 3.2)


use the floor (or ceil) function with the double to int conversions
first, it will at least round down (or up) to the nearest integer for
sure...

HTH,
Gokhan


Martin Dickopp wrote:
> 
> On Wed, Sep 18, 2002 at 10:06:51AM -0400, Hillel (Sabba) Markowitz wrote:
> > The following test program give incorrect results in a cast from
> > double to int when compiled without an optimization option but
> > correct results when compiled with an optimization option.
> >
> > int main(int argc, char **argv)
> > {
> >   int i = 128000;
> >   double f = 0.0075;
> >   double g;
> >   unsigned int u;
> >
> >   u = (unsigned int) (i*f);
> >   printf("unsigned int result of i*f: %u\n", u);
> >
> >   g = i*f;
> >   u = (unsigned int)g;
> >   printf("double result: %lf\n", g);
> >   printf("unsigned int result: %u\n", u);
> >
> >   return(0);
> > }
> >
> >
> > %gcc testfloat.c -o testfloat
> > %./testfloat
> >
> > unsigned int result of i*f: 959
> > double result: 960
> > unsigned int result: 960
> 
> You incorrectly assume that calculations involving floating-point
> numbers are infinitely precise; in reality, rounding is inevitable.
> The details of the rounding may depend, amongst other things, on the
> processor type and optimization level.
> 
> Solution:
> 
>   u = (unsigned int) (i*f + 0.5);
> 
> This rounds i*f to the nearest unsigned integer, instead of always
> rounding down. Therefore, you obtain your expected result even if
> i*f is slightly less than 960.0.
> 
> Martin

-- 
Gökhan Kisacikoglu    			     CFX
Senior Technical Director		     10950 W Washington Blvd
kisa@centropolisfx.com   310.204.7300 x263   Culver City, CA, 90232
Key: Gö(GIrl)-khan Kis(cirCUS)-a-(Art)-cik(loGIC)-og(thOUGH)-lu(fLU)


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]