Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are allowed to use "==" as seems to be the case, you can do something like that taking advantage of the fact that an exception will be raised if an array index is out of bounds. The code is for double, but you can cast any numeric type to a double (here the eventual loss of precision would not be important at all).</p> <p>I have added comments to explain the process (bring the value in ]-2.0; -1.0] union [1.0; 2.0[) and a small test driver as well.</p> <pre><code>class T { public static boolean positive(double f) { final boolean pos0[] = {true}; final boolean posn[] = {false, true}; if (f == 0.0) return true; while (true) { // If f is in ]-1.0; 1.0[, multiply it by 2 and restart. try { if (pos0[(int) f]) { f *= 2.0; continue; } } catch (Exception e) { } // If f is in ]-2.0; -1.0] U [1.0; 2.0[, return the proper answer. try { return posn[(int) ((f+1.5)/2)]; } catch (Exception e) { } // f is outside ]-2.0; 2.0[, divide by 2 and restart. f /= 2.0; } } static void check(double f) { System.out.println(f + " -&gt; " + positive(f)); } public static void main(String args[]) { for (double i = -10.0; i &lt;= 10.0; i++) check(i); check(-1e24); check(-1e-24); check(1e-24); check(1e24); } </code></pre> <p>The output is:</p> <pre><code>-10.0 -&gt; false -9.0 -&gt; false -8.0 -&gt; false -7.0 -&gt; false -6.0 -&gt; false -5.0 -&gt; false -4.0 -&gt; false -3.0 -&gt; false -2.0 -&gt; false -1.0 -&gt; false 0.0 -&gt; true 1.0 -&gt; true 2.0 -&gt; true 3.0 -&gt; true 4.0 -&gt; true 5.0 -&gt; true 6.0 -&gt; true 7.0 -&gt; true 8.0 -&gt; true 9.0 -&gt; true 10.0 -&gt; true -1.0E24 -&gt; false -1.0E-24 -&gt; false 1.0E-24 -&gt; true 1.0E24 -&gt; true </code></pre>
 

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