Comparing floats

S

saneman

I have a function:

int F(double a)
{
if (a = =1.0)
{
return 22;
}
return 44;
}


When I call F(1.0) it returns 22. But if I call F from a loop like:

double a = 0.0;
for (int j = 0; j <= 1000; j++)
{
std::cout << F(a) <<std::endl;
a = a + 0.001;
}

It returns 44 instead when 'a' reaches 1 instead of 22!

After a few hours of messing with my brains I found a website where they say
that comparing floats in C++ is not guranteed to return an expected result.
Instead something like this should be used:

if (fabs(result - expectedResult) < 0.00001)

But before I rewrite all my code that compare floats I would like to hear if
anyone has any better suggestion.
 
G

Gennaro Prota

saneman said:
I have a function:

int F(double a)
{
if (a = =1.0)
{
return 22;
}
return 44;
}


When I call F(1.0) it returns 22. But if I call F from a loop like:

double a = 0.0;
for (int j = 0; j <= 1000; j++)
{
std::cout << F(a) <<std::endl;
a = a + 0.001;
}

It returns 44 instead when 'a' reaches 1 instead of 22!

After a few hours of messing with my brains I found a website where they say
that comparing floats in C++ is not guranteed to return an expected result.
Instead something like this should be used:

if (fabs(result - expectedResult) < 0.00001)

It depends on what you want to do. Most times it is wrong as well. But
this isn't C++ specific; for starters, study the paper "What Every
Computer Scientist Should Know About Floating-Point Arithmetic", by
David Goldberg.
 
S

saneman

This is because:
1) When internally represented in binary, fractional amounts are
irrational.

2) Addition accumulates roundoff errors.

Add the following to your inner loop:

std::cout << a << std::endl;

You'll see what's happening.



I have tried doing std::cout << a << std::endl; but it just prints the
numbers from 0.001 to 1 as expected.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top