2

I have a question regarding my code. I know what I have to change in my code, but I will would like to understand why this is happening since I really want to learn the fundamentals. So my code is:

public class chunnimunni {
    public static void main(String[] args) {
         double number = 2.0;
         while (true) {
             if (number == 0.5)
                 break;
             number -= 0.1;
             System.out.printf("%8.1f", number);
         }
         System.out.println ("Finished.");
    }
}

This code will go on and print out the numbers indefinitely, it does not stop at 0.5. However if I change the while condition from:

while (true)

to

while (number > 0.5)

then it works.

If someone can explain the reason for this I would be very happy. Thanks.

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
mackanmorre
  • 145
  • 1
  • 13
  • 1
    Instead of `System.out.printf("%8.1f", number);` use `System.out.println(number);` and you will see more precise value held by `number` like `0.49999999999999933` which is not equal to `0.5` so `if (number == 0.5) break;` never happens. More at this at [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Pshemo May 31 '17 at 20:24

1 Answers1

6

Floating point numbers lack precision, so doing a comparison such as if (number == 0.5) will usually not work as expected.

Instead, I think you want if (number <= 0.5) break.

If you really wanted to do equality on floating point numbers, then you should take a difference and compare against a small number. For example,

if (Math.abs(number - 0.5) < 1E-9)
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • yeah i know this. That is why I have I have the printf condition, so that it prints out only one decimal. That is not the problem though, the question is regarding the true statement in the while loop. – mackanmorre May 31 '17 at 20:24
  • Then you don't know this, because the same rule apply to your condition. – Jazzwave06 May 31 '17 at 20:25
  • 2
    @mackanmorre: The printf doesn't matter; your'e still comparing floating-point values. Unless you compare it with some sort of epsilon value (that is, subtract the value and have it within so many decimal places of what you expect it to be), you may be stuck in a loop forever with a value that's not *quite* 0.5. – Makoto May 31 '17 at 20:25
  • @mackanmorre, The `true` statement in the `while` loop simply causes the loop to go on forever unless there is a `break`. Since the `if` check fails, the break will never happen and the loop goes on forever. – merlin2011 May 31 '17 at 20:27
  • Thanks @merlin2011, that was the answer I was looking for :) – mackanmorre May 31 '17 at 20:27
  • @mackanmorre, Please accept this answer if it resolved your question. – merlin2011 May 31 '17 at 21:11