October 24, 2011

Jupiter Jupiter
Lab Rat
95 posts

comparing doubles properly

 

Hi,

i have a problem with a piece of code:

  1. qreal a = 0.0f;
  2. Q_ASSERT(qAbs(a) == 0)

this causes sometimes to throw the assert, and sometimes not. but why? in my real there is a value like 6.0*10^-311 so its almost 0 but it is not 0, so the assert is right. but why isn’t it 0 when i initialized it with 0?

4 replies

October 24, 2011

Lukas Geyer Lukas Geyer
Gene Splicer
2074 posts

This is due to limited precision of floating point numbers. Use qFuzzyCompare() [doc.qt.nokia.com] instead.

October 27, 2011

Jupiter Jupiter
Lab Rat
95 posts

thanks.

I also found the method qFuzzyIsNull() its not in the doc, but compares the parameter with 0.0 thats exactly what i need

October 27, 2011

ardhitama ardhitama
Lab Rat
7 posts

  1. qreal a = 0.0f;
  2. Q_ASSERT(qAbs(a) < 1e-8 && qAbs(a) > 0.0f)

Comparing to real number to zero is almost not possible in reality, but if you dare, you could also try this:

  1. qreal a = 0.0f;
  2. Q_ASSERT(qAbs(a) == 0.0f)

 Signature 

Love automagically stuffs

October 27, 2011

Volker Volker
Robot Herder
5428 posts

Jupiter wrote:
thanks.

I also found the method qFuzzyIsNull() its not in the doc, but compares the parameter with 0.0 thats exactly what i need

qFuzzyIsNull is declared internal in the sources. Usually that’s for a reason…

You might want to open a request to make it officially public in the bug tracker [bugreports.qt.nokia.com] though.

 
  ‹‹ QLocalServer with Win32 pipe      New to Qt, question about code converstion ››

You must log in to post a reply. Not a member yet? Register here!