Re: (Pi/2. ) != (90.0 DegToRad)

From: Christophe Delaere <christophe.delaere_at_cern.ch>
Date: Thu, 21 Dec 2006 15:08:55 +0100


Hi,

As a general rule, you should avoid using the == and != operators with floats and doubles.
Due to the way these quantities are handled by the compiler and the CPU, the outcome of such operators is often unpredictable.

If you have to test equality of two floating point values, it's better to to something like:
if(fabs(a-b)<epsilon) { /* do sth. */}
where epsilon is defined to be small with respect to the quantities you are handling.

Best,
Christophe.

On Thursday 21 December 2006 12:31, you wrote:
> Hello,
>
> I have been working with some trigonometric functions of the
> "TMath"-Class when I discovered a peculiar behaviour of ROOT v5.0.12e.
> I have appended a stand-alone piece of my code. The comments at the end
> show my output when compiling or interpreting.
> While interpreting with Cint, everything is okay, but when I compile it,
> the following comparison is astonishing to me:
>
> "Double_t phi=90.0*TMath::DegToRad();
> if (phi==TMath::Pi()/2.0) returns "false",
> while if(phi==TMath::PiOver2()) returns true?! "
>
> Much more interesting is the fact, that:
> "Double_t phi=90.0*TMath::DegToRad();
> cout<<phi<<endl;
> if (phi==TMath::Pi()/2.0) now returns "true" - instead of "cout" e.g.
> an empty "for"-loop is possible and still returns "true", a variable
> declaration as "Int_t a=5" returns "false" and "Double_t
> b=TMath::Cos(5.)" returns "true" again.
>
> Any ideas?
> As you can see in my code, I tried a lot of possibilities (casting the
> numbers to doubles, updating ROOT to version 5.0.14 etc.) without
> success. Please tell me whats wrong or how to prevent this infelicitous
> situation.
>
> Best regards,
> Kathrin Stoerig
>
> -------------------------------------------------------------------
>
> Kathrin Störig
>
> II.Physikalisches Institut
>
> Universitaet Goettingen Telefon:
> +49 551 39 12214
>
> Friedrich-Hund Platz 1 D-37077 Goettingen Telefax: +49 551 39 4493
>
> Kathrin.Stoerig_at_phys.uni-goettingen.de
> <mailto:Kathrin.Stoerig_at_phys.uni-goettingen.de>
>
> --------------------------------------------------------------------

-- 
Christophe DELAERE
CERN fellow
Tel   : 74307 (from outside: +41 22 76 74307 ) 
Office: 28 1-030 Mailbox: G06100
E-mail: christophe.delaere_at_cern.ch
Home  : http://www.fynu.ucl.ac.be/users/c.delaere
Received on Thu Dec 21 2006 - 15:08:33 MET

This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:32:02 MET