About 2.0-1.1 in Java! = 0.9 problem

About 2.0-1.1 in Java! = 0.9 problem

Question leads to:

About floating-point value computing section mentioned in the "Java core technology" in System.out.println(2.0-1.1)this statement is not taken for granted 0.9, but 0.8999999999999999, it would not be very surprised, because I know about: floating-point values to represent binary form, resulting in a portion of the lost bits. However, I do not really know the details, so it took some time to read some of the articles written by senior Daniel, have a certain understanding, hereby record the following.

I also try to do the following:

System.out.println(0.01f+0.04f);//输出0.049999997
System.out.println(0.01f+0.04);//输出0.04999999977648258
System.out.println(2.0-1.1);//输出0.8999999999999999
System.out.println(2.0f-1.1f);//输出0.9
System.out.println(2.0-0.1);//输出1.9

Some conclusions:

  • Converted into a binary integer and fractional number of different mechanisms. In addition to two integers modulo until 1 whom, certainly not an infinite loop, it is possible to accurately represented in binary. But different fractional, the fractional part multiplied by 2, rounded part, and then multiplied by the fractional part 2 ... until the fractional part is zero so far, there is a chance to go on an endless loop.
  • In Java it will not declare a default type of decimals as a double process, which is the statement of the case 3. 4 The statement declared value type is float, because the loss of the inherent accuracy, but output 0.9.
  • 1 and 2 statements statements 0.01f output difference is the difference in accuracy, specific reference links: [doubts] Analysis float type memory storage problems and loss of accuracy
  • The statement 5 is also adding two double type, why output is "correct" it, refer to: Why in java 2.0-1.1 2.0-0.1 = 0.899999 ... but it may be = 1.9? The answer.

Guess you like

Origin www.cnblogs.com/summerday152/p/11842680.html