Search code examples
binarydoublecomputer-sciencebreakrepresentation

How to know when a float variable is going to stop increasing by 0.001?


I want to know how to determine at wich value a float (or double) variable is going to stop increasing its value if I am increasing it by 0.001.

If we talk about the binary representation of the float value: 1 bit for Sign, 8 exponent bits and 23 bits for mantissa. We know that when we reach a determined high value (32768) and then we add a very small value (0.001), due to the EXC 127 representation of the exponent, the addition result will be:

32768 + 0 = 32768

According to that, the variable will have the same value eventhough we are adding 0.001.

The next code never breaks.

float max =100000;
float delta=0.001F;
float time = 0;
while (time < max)
{
time += delta;
if(time == max)
    break;
}

Can someone help me to determine an ecuation to know when a variable is going to stop increasing? (Independently if it is a float or a double, the idea is to have a floating comma variable).


Solution

  • Your addition will become idempotent (that is, the result will not change) after time gets large enough that the size of its ULP (unit in the last place) is greater than the size of your delta.