Floating point voodoo #1

This is kind of cool:

float Lifetime = FLT_MAX;  // Use FLT_MAX for “infinite lifetime”
Lifetime -= 1.0f;                // Or elapsed time or whatever, small value

=> the IEEE float machinery is such that “Lifetime” doesn’t change in this case. So an infinite lifetime is really infinite, automagically :)

2 Responses to “Floating point voodoo #1”



  1. JHoule Says:

    Actually, you can do slightly better by actually using infinity, which exists in the IEEE representation.

    The following code gives an example:

    float f = numeric_limits::max();
    float f1 = f - 1.0f;
    float f2 = f * 0.5f;
    float f3 = f - powf(2.0f, 103.0f);
    cout << f << " " << (f == f1) << " " << (f == f2) << " " << (f == f3) << endl;

    f = numeric_limits::infinity();
    f1 = f - 1.0f;
    f2 = f * 0.5f;
    f3 = f - powf(2.0f, 103.0f);
    cout << f << " " << (f == f1) << " " << (f == f2) << " " << (f == f3) << endl;

    As you can notice, your FLT_MAX (described above using the numeric_limits scheme in C++) is a finite value which can actually be affected by a sufficiently large value (or by scaling).

    On the other hand, if you use the actual representation of infinity, it will stay unaffected by those operations.

    The hexadecimal representation of +inf is 0×7F800000 (fill the exponent with 1s and fill the mantissa with 0s), so if you don’t want to use numeric_limits, you can always typecast an int’s bits into a float (I believe C has no standard #define for infinity).

  2. admin Says:

    Yes, you can also use +INF for this. I usually avoid it because I never remember if there’s an extra cost associated with it (like there is with NaNs). Just in case, I prefer avoiding those special float values. But it might just be paranoia :)

shopfr.org cialis