Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - infinite while loop with float [duplicate]

I am currently learnig java float-point numbers. I know, that a float have a specific amount of significant digets. I also know, that a float is represented in java like -1 or 1 * num * 10^x. Where num is the numer and 10^x is the decimal "point". But here we do not have a fraction of a number. How is a infinite loop here possible?

The code with infinite loop:

float f = 123456789;
while (f-- > 0) {
System.out.println(f);
}
like image 305
Charlie Avatar asked Jan 01 '17 10:01

Charlie


1 Answers

It's about floating point arithmetic. When you're decrementing the number you stumble upon the situation when you go through the number f = 1.23456792E8 makes everything go wrong, because f-1 and f have the same floating point representation here. So decrementing makes the number be itself, which leads to the infinite loop. Just check:

System.out.println(1.23456792E8f);
System.out.println(1.23456792E8f - 1);

What is so special about the number and why execution stops there? It's because the floating point representation of 123456789 is 1.23456792E8. Already this gives us a gap of at least 3 due to the lack of precision of floating point numbers. Using double instead of float makes the program finish, but the issue will occur with higher numbers.

like image 165
Adrian Jałoszewski Avatar answered Oct 13 '22 03:10

Adrian Jałoszewski