Daqs
Daqs

Reputation: 964

FOR loop iteration not working

I am simply trying to get the output from a FOR loop, where the initialized value i is iterated over 3 times.

remainder = 0.33F;

for (float i = 0; i < 1.00F; i += remainder)
{
  Debug.Log(i);
}

This is giving output, as i = 0, i = 0.33 and i=0.66. Why am I not getting i = 0.99?

Upvotes: 1

Views: 109

Answers (1)

Max Yankov
Max Yankov

Reputation: 13297

Because float point arithmetic isn't precise, and shouldn't expected to be.

Precise explanation of this particular problem would include details of how floats a stored in memory in the C# VM, and how it's different between Microsoft's compiler and Mono's compiler, and how you could get different results if you built on iOS, before and after IL2CPP.

However, I don't think that you need all this information, and to be honest, I'm too lazy to dig this deep. Just as a general rule of thumb, rely on float point arithmetic to be unreliable and imprecise.

Upvotes: 1

Related Questions