Skip to content
Jun 21 / Danushka

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…

3 Comments

leave a comment
  1. Ed Smith-Rowland / Apr 17 2010

    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.

  2. Jonathan / Aug 16 2011

    I agree with Ed. Isn’t that what min was supposed to do?

Trackbacks and Pingbacks

  1. EOP Exercise Round-Up: Chapter 2 « C++Next
Leave a Comment