Tracy Nelson on Mon, 22 Nov 1999 18:18:04 -0500 (EST)


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

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


Nicolai Rosen wrote:
> 
> 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;
> }

He might even be better off just declaring constants for the powers of
ten that he's using.  I almost always do that for integer exponents,
because pow() is such a pig.

As an alternate approach, have you thought about declaring a stucture to
represent the floating-point format you're using (I assume it's the
Intel 80-bit FP format) and extracting the information from that?

If you're going to work with FP to any extent (or if you're going to be
a professional programmer someday), you *have* to read this paper.  It's
got more than any reasonable programmer would want to know about the
shortcomings and tricks to working with floating-point numbers: _What
Every Computer Scientist Should Know About Floating-Point Arithmetic_. 
Available at:
http://www.sns.ias.edu/Main/computing/compilers_html/common-tools/numerical_comp_guide/goldberg1.doc.html

Do yourself a favor, print this out and save it somewhere, because it
*will* come in handy someday.
-- 
Just junk food for thought...

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