This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: linux i-86 problem with rounding (gcc-3.1.1 & 3.2)
- From: Gokhan Kisacikoglu <kisa at centropolisfx dot com>
- To: Martin Dickopp <firefly-mail at gmx dot net>
- Cc: "Hillel (Sabba) Markowitz" <sabbahem at bcpl dot net>, GCC Help <gcc-help at gcc dot gnu dot org>
- Date: Wed, 18 Sep 2002 09:58:42 -0700
- Subject: Re: linux i-86 problem with rounding (gcc-3.1.1 & 3.2)
- Organization: Centropolis Effects, LLC
- References: <3DA44C07@webmail.bcpl.net> <20020918164648.GA878@feynman.quark-gluon-plasma.xyz>
- Reply-to: kisa at centropolisfx dot com
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)