Re: round(50.5) = 50

From: Philipp Matthias Hahn <Philipp(dot)Hahn(at)informatik(dot)uni-oldenburg(dot)de>
To: Peter Eisentraut <peter_e(at)gmx(dot)net>
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: round(50.5) = 50
Date: 2004-03-01 07:53:13
Message-ID: 4042EBE9.9010805@informatik.uni-oldenburg.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Peter Eisentraut wrote:
> Philipp Matthias Hahn wrote:
>
>># SELECT round(5.5::float4),round(50.5::float4);
>> round | round
>>-------+-------
>> 6 | 50
>>(1 row)
>>
>>I think this is a bug, since I would expect 6 and 51.
>
> The default rounding mode for floating point (determined by your C
> library, mostly) it to round toward the closest even number.

No, see program and its results below.
If you don't cast the numbers above to "float4", you get the correct
results "6" and "51". Something is broken with casting "float8" to
"float4", since there is no numerical problem representing .5 either in
float4 or float8.

$ dpkg -l libc6 gcc | tail -2
ii libc6 2.3.2.ds1-11 GNU C Library: Shared libraries
ii gcc 3.3.2-2 The GNU C compiler
$ cat x.c
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define rf(f) printf("roundf(%f)=%f lroundf(%f)=%ld\n", f, roundf(f), f,
lroundf(f));
#define rd(d) printf("round(%lf)=%lf lround(%lf)=%ld\n", d, round(d), d,
lround(d));

int main(void) {
rf(5.5f);
rf(50.5f);
rd(5.5);
rd(50.5);
}
$ gcc -lm -std=c99 -Wall x.c
$ ./a.out
roundf(5.500000)=6.000000 lroundf(5.500000)=6
roundf(50.500000)=51.000000 lroundf(50.500000)=51
round(5.500000)=6.000000 lround(5.500000)=6
round(50.500000)=51.000000 lround(50.500000)=51

> If you are at all concerned abou that, you probably shouldn't be
> using floating point, but rather numeric.

Yes, I did switch back to numeric, which solved this problem. I
originally switched from numeric(4,1) to float, because I had trouble
with Java and Cocoon.

BYtE
Philipp
--
Dipl.-Inform. Philipp(dot)Hahn(at)informatik(dot)uni-oldenburg(dot)de
Abteilung Systemsoftware und verteilte Systeme, Fk. II
Carl von Ossietzky Universitaet Oldenburg, 26111 Oldenburg, Germany
http://www.svs.informatik.uni-oldenburg.de/contact/pmhahn/
Telefon: +49 441 798-2866 Telefax: +49 441 798-2756

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message pgsql-bugs 2004-03-01 13:31:18 Returned due to virus; was: Re: Re: Thanks!
Previous Message Margit Schubert-While 2004-02-29 20:22:45 Re: ecpg segmentation error