Nicolai Rosen on Sat, 20 Nov 1999 15:07:50 -0500 (EST)


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

Re: [Plug] Strange floating point behavior with C++


The problem is that you're assuming that pow(10,a) raises 10 to the ath power the same way you or I would. It doesn't. As a result, you get an answer that is slightly off. Ordinarily this wouldn't matter, but because you're trying to get an exact integer answer. I'd reccomend making your own function for that. Make something like:

float lower10(int power){
  float result=1;

  for(;power<0;power++)
     result/=10;

  return result;
}

Oh, & as an aside, if you want to return the number of decimal places, shouldn't that be -a?

From: Morgan Wajda-Levie <mpwl@locke.ccil.org>
Reply-To: plug@lists.nothinbut.net
To: Plug <plug@lists.nothinbut.net>
Subject: [Plug] Strange floating point behavior with C++
Date: Sat, 20 Nov 1999 14:52:56 -0500

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
<< attach3 >>

______________________________________________________ Get Your Private, Free Email at http://www.hotmail.com

_______________________________________________
Plug maillist  -  Plug@lists.nothinbut.net
http://lists.nothinbut.net/mail/listinfo/plug