From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 22788 invoked by alias); 18 Sep 2002 16:59:05 -0000 Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org Received: (qmail 22770 invoked from network); 18 Sep 2002 16:59:03 -0000 Received: from unknown (HELO mail.centropolisfx.com) (64.70.30.98) by sources.redhat.com with SMTP; 18 Sep 2002 16:59:03 -0000 Received: from centropolisfx.com (jupiter.centropolisfx.com [172.20.2.83]) by mail.centropolisfx.com (8.11.3/8.11.3) with ESMTP id g8IGwl5802467; Wed, 18 Sep 2002 09:58:47 -0700 (PDT) Message-ID: <3D88B0C2.E868165D@centropolisfx.com> Date: Wed, 18 Sep 2002 09:59:00 -0000 From: Gokhan Kisacikoglu Reply-To: kisa@centropolisfx.com Organization: Centropolis Effects, LLC X-Accept-Language: en MIME-Version: 1.0 To: Martin Dickopp CC: "Hillel (Sabba) Markowitz" , GCC Help Subject: Re: linux i-86 problem with rounding (gcc-3.1.1 & 3.2) References: <3DA44C07@webmail.bcpl.net> <20020918164648.GA878@feynman.quark-gluon-plasma.xyz> Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit X-SW-Source: 2002-09/txt/msg00131.txt.bz2 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)