Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If floats are 32-bit IEEE-754 and ints are 32-bit too and if there are no +infinity, -infinity and <code>NaN</code> values, we can compare floats as ints with a little trick:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; #include &lt;assert.h&gt; #define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1] C_ASSERT(sizeof(int) == sizeof(float)); C_ASSERT(sizeof(int) * CHAR_BIT == 32); int isGreater(float* f1, float* f2) { int i1, i2, t1, t2; i1 = *(int*)f1; i2 = *(int*)f2; t1 = i1 &gt;&gt; 31; i1 = (i1 ^ t1) + (t1 &amp; 0x80000001); t2 = i2 &gt;&gt; 31; i2 = (i2 ^ t2) + (t2 &amp; 0x80000001); return i1 &gt; i2; } int main(void) { float arr[9] = { -3, -2, -1.5, -1, 0, 1, 1.5, 2, 3 }; float thr; int i; // Make sure floats are 32-bit IEE754 and // reinterpreted as integers as we want/expect { static const float testf = 8873283.0f; unsigned testi = *(unsigned*)&amp;testf; assert(testi == 0x4B076543); } thr = -1.5; for (i = 0; i &lt; 9; i++) { printf("%f %s %f\n", arr[i], "&lt;=\0&gt; " + 3*isGreater(&amp;arr[i], &amp;thr), thr); } thr = 1.5; for (i = 0; i &lt; 9; i++) { printf("%f %s %f\n", arr[i], "&lt;=\0&gt; " + 3*isGreater(&amp;arr[i], &amp;thr), thr); } return 0; } </code></pre> <p>Output:</p> <pre><code>-3.000000 &lt;= -1.500000 -2.000000 &lt;= -1.500000 -1.500000 &lt;= -1.500000 -1.000000 &gt; -1.500000 0.000000 &gt; -1.500000 1.000000 &gt; -1.500000 1.500000 &gt; -1.500000 2.000000 &gt; -1.500000 3.000000 &gt; -1.500000 -3.000000 &lt;= 1.500000 -2.000000 &lt;= 1.500000 -1.500000 &lt;= 1.500000 -1.000000 &lt;= 1.500000 0.000000 &lt;= 1.500000 1.000000 &lt;= 1.500000 1.500000 &lt;= 1.500000 2.000000 &gt; 1.500000 3.000000 &gt; 1.500000 </code></pre> <p>Of course, it makes sense to precalculate that final integer value in <code>isGreater()</code> that's used in the comparison operator if your threshold doesn't change.</p> <p>If you are afraid of undefined behavior in C/C++ in the above code, you can rewrite the code in assembly.</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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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