Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange double rounding issue
    primarykey
    data
    text
    <p>I came across the following silly function <a href="http://www.artima.com/forums/flat.jsp?forum=106&amp;thread=338926&amp;start=0&amp;msRange=15" rel="nofollow">here</a>:</p> <pre><code>public static String findOutWhatLifeIsAllAbout() { int meaning = 0; for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 20; j++) { for (int k = 0; k &lt; 300; k++) { for (int m = 0; m &lt; 7000; m++) { meaning += Math.random() + 1; } } } } return String.valueOf(meaning).replaceAll("0*$", ""); } </code></pre> <p>In summary, the expected result is a string "42", since Math.random() returns doubles "greater than or equal to 0.0 and less than 1.0". In practice, running on an i5 under Ubuntu the resulting strings are similar to "420000011", "420000008"! (meaning sometimes Math.random()'s result is getting <em>rounded up</em>!</p> <p>To get a grip on what sorts of double values would cause Math.random()'s result to somehow <em>round</em> to 1, I tried this function instead, expecting to see some examples.</p> <pre><code>public static String findOutWhatLifeIsAllAboutAltered() { int meaning = 0; for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 20; j++) { for (int k = 0; k &lt; 300; k++) { for (int m = 0; m &lt; 7000; m++) { double randomResult = Math.random(); int converted = randomResult; if (converted &gt; 0) { System.out.println("Misbehaving double = " + randomResult); } meaning += converted + 1; } } } } return String.valueOf(meaning).replaceAll("0*$", ""); } </code></pre> <p>However this formulation always returns "42"! Can anyone offer insight about why the behavior changes in the altered function? Thanks.</p> <p>Furthermore why does Java let the original function compile at all? Shouldn't there be a loss-of-precision error at the <code>+=</code> call?</p> <p><em>edit</em> posted the code I wanted you all to see - the "original" version wasn't supposed to have a cast.</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.
 

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