Java Infinite while Loop - float 123456789

I am currently studying java floating point numbers. I know that a float has a certain amount of significant resources. I also know that float is represented in java as -1 or 1 * num * 10 ^ x. Where num is a number and 10 ^ x is the decimal point. But here we do not have a fraction of the number. How is an infinite loop possible?

Endless loop code:

float f = 123456789; while (f-- > 0) { System.out.println(f); } 
+6
source share
1 answer

This is about floating point arithmetic. When you reduce the number that you come across the situation when you pass the number f = 1.23456792E8 , everything goes wrong, because f-1 and f have the same floating point representation. Thus, decrementation makes the number itself, which leads to an infinite loop. Just check:

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

What is so special about quantity and why does execution stop? This is because the 123456789 floating point representation is 1.23456792E8 . This already gives us a space of at least 3 due to the lack of precision of floating point numbers. Using double instead of float makes the program complete, but the problem will occur with higher numbers.

+4
source

Source: https://habr.com/ru/post/1013682/


All Articles