Note that there are some explanatory texts on larger screens.

plurals
  1. POfloat/double equality with exact zero
    primarykey
    data
    text
    <p>I have an algorithm which uses <code>floats</code> or <code>doubles</code> to perform some calculations.</p> <p>Example:</p> <pre><code>double a; double b; double c; ... double result = c / (b - a); if ((result &gt; 0) &amp;&amp; (result &lt; small_number)) { // result is relevant... } else { // result not required... } </code></pre> <p>Now, I am worried about <code>(b - a)</code> might be zero. If it is close to zero but not zero, it does not matter because the <code>result</code> will be out of range to be useful, and I already detect that (as <code>(b - a)</code> approaches zero, <code>result</code> will approach +/- inf, which is not in the range <code>0</code>-<code>small_number</code>...)</p> <p>But if the result of <code>(b - a)</code> is exactly zero, I expect that something platform dependant will happen due to divide by zero. I could change the <code>if</code> statement to:</p> <pre><code>if ((!((b-a) == 0.0)) &amp;&amp; ((result = c/(b-a)) &gt; 0) &amp;&amp; (result &lt; small_number)) { </code></pre> <p>but I don't know if <code>(b-a) == 0.0</code> will always detect equality with zero. I have seen there are multiple representations for exact zero in floating point? How can you test for them all without doing some epsilon check, which I don't need (a small epsilon will be ignored in my algorithm)?</p> <p>What is the platform independant way to check?</p> <p><strong>EDIT:</strong></p> <p>Not sure if it was clear enough to people. Basically I want to know how to find if an expression like:</p> <pre><code>double result = numerator / denominator; </code></pre> <p>will result in a floating point exception, a cpu exception, a signal from the operating system or something else.... without actually performing the operating and seeing if it will "throw"... because detecting a "throw" of this nature seems to be complicated and platform specific.</p> <p>Is <code>( (denominator==0.0) || (denominator==-0.0) ) ? "Will 'throw'" : "Won't 'throw'";</code> enough?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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