Morgan Wajda-Levie on Sat, 20 Nov 1999 13:48:47 -0500 (EST)


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

[Plug] Strange floating point behavior with C++


I know that this is not a C programming mailing list, but a lot of
Linux people know C, and this is C code being written on Linux, so
it's somewhat applicable.

I'm writing a function in C++ that takes a floating point number and
returns the number digits of precision it has.  I'm doing this with
the following code:

  int f_digits(float number)
  {
    int a;
    number -= int(number);
    if(!number) return(0);
    for(a = 0; int(number / pow(10, a)) != number / pow(10, a); a--)
      {
      }
    return(a);
  }

As far as I can tell, the code looks like it should work.  If the
number has two digits of precision, it should be evenly divisible by
10^-2, or 10.01.  Instead, it loops infinitely.  By running it through
gdb, I find that it claims that number = 0.400024414, when it should
be .4.  (123.4 - 123).  I tried dividing this number by 10^-9 in the
debugger, and I wrote everything out by hand.  Somehow, it came up
with the following:

.400024414 / .000000001
$4 = 400024413.99999994

Why can't C++ use floating point numbers accurately?

Also, for system info: I'm running Debian potato with glibc 2.1.2-10
and gcc 2.95.2-3.
-- 
Morgan Wajda-Levie
http://www.worldaxes.com/wajdalev
PGP fingerprint:
A353 C750 660E D8B6 5616  F4D8 7771 DD21 7BF6 221C
http://www.worldaxes.com/wajdalev/public.asc for PGP key
encrypted mail preferred

Attachment: pgpSuvUkY03tg.pgp
Description: PGP signature