title: Safe Floating Point Division
body: <p>I have some places in my code where I want to assure that a division of 2 arbitrary floating point numbers (32 bit single precision) won't overflow. The target/compiler does not guarantee (explicitly enough) nice handling of -INF/INF and (does not fully guarantees IEEE 754 for the exceptional values - (possibly undefined) - and target might change). Also I cannot make save assumtions on the inputs for this few special places and I am bound to C90 standard libraries.</p>
  
  <p>I have read <a href="http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a> but to be honest, I am a little bit lost.</p>
  
  <p>So... I want to ask the community, if the following piece of code would do the trick, and if there are better/faster/exacter/correcter ways to do it:</p>
  
  <pre><code>#define SIGN_F(val) ((val &gt;= 0.0f)? 1.0f : -1.0f)
  
  float32_t safedivf(float32_t num, float32_t denum)
  {
     const float32_t abs_denum = fabs(denum);
     if((abs_denum &lt; 1.0f) &amp;&amp; ((abs_denum * FLT_MAX) &lt;= (float32_t)fabs(num))
         return SIGN_F(denum) * SIGN_F(num) * FLT_MAX;
     else
         return num / denum;
  }
  </code></pre>
  
  <hr>
  
  <p>Edit: Changed <code>((abs_denum * FLT_MAX) &lt; (float32_t)fabs(num))</code> to <code>((abs_denum * FLT_MAX) &lt;= (float32_t)fabs(num))</code> as recommeded by Pascal Cuoq.</p>