Note that there are some explanatory texts on larger screens.

plurals
  1. POFloating point rounding when truncating
    text
    copied!<p>This is probably a question for an x86 FPU expert:</p> <p>I am trying to write a function which generates a random floating point value in the range [min,max]. The problem is that my generator algorithm (the floating-point Mersenne Twister, if you're curious) only returns values in the range [1,2) - ie, I want an inclusive upper bound, but my "source" generated value is from an exclusive upper bound. The catch here is that the underlying generator returns an 8-byte double, but I only want a 4-byte float, and I am using the default FPU rounding mode of Nearest.</p> <p>What I want to know is whether the truncation itself in this case will result in my return value being inclusive of max when the FPU internal 80-bit value is sufficiently close, or whether I should increment the significand of my max value before multiplying it by the intermediary random in [1,2), or whether I should change FPU modes. Or any other ideas, of course.</p> <p>Here's the code I am currently using, and I did verify that 1.0f resolves to 0x3f800000:</p> <pre><code>float MersenneFloat( float min, float max ) { //genrand returns a double in [1,2) const float random = (float)genrand_close1_open2(); //return in desired range return min + ( random - 1.0f ) * (max - min); } </code></pre> <p>If it makes a difference, this needs to work on both Win32 MSVC++ and Linux gcc. Also, will using any versions of the SSE optimizations change the answer to this?</p> <p><strong>Edit:</strong> The answer is yes, truncation in this case from double to float is sufficient to cause the result to be inclusive of max. See Crashworks' answer for more.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload