Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think the following works, but I will state my assumptions first:</p> <ul> <li>floating-point numbers are stored in IEEE-754 format on your implementation,</li> <li>No overflow,</li> <li>You have <code>nextafterf()</code> available (it's specified in C99).</li> </ul> <p>Also, most likely, this method is not very efficient.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; int main(int argc, char *argv[]) { /* Change to non-zero for superior, otherwise inferior */ int superior = 0; /* double value to convert */ double d = 0.1; float f; double tmp = d; if (argc &gt; 1) d = strtod(argv[1], NULL); /* First, get an approximation of the double value */ f = d; /* Now, convert that back to double */ tmp = f; /* Print the numbers. %a is C99 */ printf("Double: %.20f (%a)\n", d, d); printf("Float: %.20f (%a)\n", f, f); printf("tmp: %.20f (%a)\n", tmp, tmp); if (superior) { /* If we wanted superior, and got a smaller value, get the next value */ if (tmp &lt; d) f = nextafterf(f, INFINITY); } else { if (tmp &gt; d) f = nextafterf(f, -INFINITY); } printf("converted: %.20f (%a)\n", f, f); return 0; } </code></pre> <p>On my machine, it prints:</p> <pre><code>Double: 0.10000000000000000555 (0x1.999999999999ap-4) Float: 0.10000000149011611938 (0x1.99999ap-4) tmp: 0.10000000149011611938 (0x1.99999ap-4) converted: 0.09999999403953552246 (0x1.999998p-4) </code></pre> <p>The idea is that I am converting the <code>double</code> value to a <code>float</code> value&mdash;this could be less than or greater than the double value depending upon the rounding mode. When converted back to <code>double</code>, we can check if it is smaller or greater than the original value. Then, if the value of the <code>float</code> is not in the right direction, we look at the next <code>float</code> number from the converted number in the original number's direction.</p>
    singulars
    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