Danushka "silvermace" Abeysuriya

fun with numeric_limits min

Just a quick note, I thought others might find this helpful as well. In our level compiler, a bug which somehow went un-noticed for a little while was causing bounding boxes to not be calculated properly. This turned out to be a simple initialization oversight.

Vec3 maxValue, minValue;

ofcourse the default constructor would initialize both vectors to [0,0,0]. This is useless when trying to determine a bounding box which lies entirely in the negative part of all axies (because no vertex in that area will ever excede maxValue, which has incorrectly been initalized to zero). The fix was simple, but it reminded me of another C/C++ quirk over numeric limits.

The fix, one would think, would be something like this:

const float FLOAT_HIGHEST = std::numeric_limits<float>::max();
const float FLOAT_LOWEST = std::numeric_limits<float>::min();
Vec3 maxValue(FLOAT_HIGHEST, FLOAT_HIGHEST, FLOAT_HIGHEST);
Vec3 maxValue(FLOAT_LOWEST, FLOAT_LOWEST, FLOAT_LOWEST);

But, you’de be wrong. If you were using numeric_limits<int> that would work fine, but numeric_limits<float>::min acutally returns the lowest representable positive float (this is to help calculate another issue with IEEE floats see: http://en.wikipedia.org/wiki/Denormal).

Boost provides a clean solution for this in their “bounds” package.

I’m tempted to just go “-numeric_limits<float>::max()” (that is pretty much what the boost code will compile down to) but I like consistency, and I don’t want to worry about any (if any exist?) unmatched upper and lower values like 32 bit signed ints have, I’m no float expert…

1 Comment to fun with numeric_limits min

  1. Ed Smith-Rowland's Gravatar Ed Smith-Rowland
    April 17, 2010 at 4:41 pm | Permalink

    I always thought this was strange and couterintuitive.
    They added std::numeric_limits::lowest() to C++-0x that does what min *really* should have done.

  1. By on April 10, 2010 at 11:50 pm

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>