Hesham Adel
Hesham Adel

Reputation: 367

Loop with float iteration

First Situation

for (int i = 0 ; i <=2 ; i++)
{
    cout << i << endl ;
}

output:

1
2

Second Situation

for (float i = 0 ; i <= 2 ; i+=.2)
{
    cout << i << endl;
}

output

1
1.2
1.4
1.6
1.8

The question is why in the second situation he didn't take the 2 even i said ( <= ) and the funny thing if i remove the = the output will be even the same ?

Constrains i have to use the float DataType and i want to use the <= Operator

Upvotes: 0

Views: 1281

Answers (2)

Dakorn
Dakorn

Reputation: 903

You cannot compare float or double variables using == because of possible arithmetic rounding errors. You should use epsilon.

const float EPSILON = 0.00001f;
for (float f = 0.0f; EPSILON > std::fabs(f - 2.0f); f += 0.2f)
{
std::cout << f << std::endl;
}

Also try use lireral f when you are using float type (float my_float = 12.4f;).

Upvotes: 0

fjardon
fjardon

Reputation: 7996

Because 0.2 doesn't fit exactly in a float and you accumulate floating point errors in your loop. On my computer accumulating 10 times 0.2 is 2.38419e-07 above 2.0f

Upvotes: 1

Related Questions