Java – the principle of Least Surprise [copy]

See English answers > java double precision 2

double d = 0.0;
    for (int i = 0; i < 10; i++)
    {
        d = d+0.1;
    }
    System.out.println(d);

This is an example of my reading on the "minimum surprise principle"

I just wonder why the code returns 0.99999999. If I change the data type of D to float, I get 1.0000001 What are the reasons behind this behavior?

Solution

This is a classic case of imprecise floating point numbers Since 0.1 cannot be represented cleanly in binary form (it is a repeated number), there is a rounding error as the number is repeatedly added to itself When we change to floating point numbers, the difference in behavior only boils down to the difference of actually maintaining 0.1 in more bit stored procedures

If you need a very precise decimal representation, the BigDecimal class will soon become your best friend Based on how it stores decimal details internally without losing accuracy, the calculation can maintain its integrity

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>