Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Inaccuracy using double
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/322749/retain-precision-with-doubles-in-java">Retain precision with Doubles in java</a><br> <a href="https://stackoverflow.com/questions/327544/strange-floating-point-behaviour-in-a-java-program">Strange floating-point behaviour in a Java program</a> </p> </blockquote> <p>I'm making a histogram class, and I'm encountering a weird issue.</p> <p>Here are the basics of the class, there are more methods but they aren't relevant to the issue.</p> <pre><code>private int[] counters; private int numCounters; private double min, max, width; public Histogram(double botRange, double topRange, int numCounters) { counters = new int[numCounters]; this.numCounters = numCounters; min = botRange; max = topRange; width = (max - min) / (double) numCounters; } public void plotFrequency() { for (int i = 0; i &lt; counters.length; i++) { writeLimit(i * width, (i + 1) * width); System.out.println(counters[i]); } } private void writeLimit(double start, double end) { System.out.print(start + " &lt;= x &lt; " + end + "\t\t"); } </code></pre> <p>the problem happens when I plot the frequencies. I've created 2 instances. new Histogram(0, 1, 10); new Histogram(0, 10, 10);</p> <p>This is what they output.</p> <pre><code>Frequecy 0.0 &lt;= x &lt; 0.1 989 0.1 &lt;= x &lt; 0.2 1008 0.2 &lt;= x &lt; 0.30000000000000004 1007 0.30000000000000004 &lt;= x &lt; 0.4 1044 0.4 &lt;= x &lt; 0.5 981 0.5 &lt;= x &lt; 0.6000000000000001 997 0.6000000000000001 &lt;= x &lt; 0.7000000000000001 1005 0.7000000000000001 &lt;= x &lt; 0.8 988 0.8 &lt;= x &lt; 0.9 1003 0.9 &lt;= x &lt; 1.0 978 Frequecy 0.0 &lt;= x &lt; 1.0 990 1.0 &lt;= x &lt; 2.0 967 2.0 &lt;= x &lt; 3.0 1076 3.0 &lt;= x &lt; 4.0 1048 4.0 &lt;= x &lt; 5.0 971 5.0 &lt;= x &lt; 6.0 973 6.0 &lt;= x &lt; 7.0 1002 7.0 &lt;= x &lt; 8.0 988 8.0 &lt;= x &lt; 9.0 1003 9.0 &lt;= x &lt; 10.0 982 </code></pre> <p>So my question is, why am I getting the really long decimal limits in the first example, but not the second one?</p>
    singulars
    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