Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

findbugs - Today I am facing very abnormal bug in android code

I am trying to substract 1.0f from 8.6f value and it returns me 7.6000004

float temp=8.6f-1.0f;
Log.e("temp",temp+"");

and it is printing 7.6000004 What was wrong here ? I am or Android ?

question from:https://stackoverflow.com/questions/65919793/today-i-am-facing-very-abnormal-bug-in-android-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Floating point operations such like this aren't precise; this is a well-known problem in computer science. See also: https://floating-point-gui.de/basic/

It's basically the same problem as if someone asks you to give a precise answer to "What's 1 divided by 3, to 10 decimal places?" - the best answer you could give is 0.3333333334.

But 3 * 0.3333333334 = 1.0000000002

It's a limitation that exists in every number system, just in different cases.

If you need exact numbers, you should use BigDecimal:

import java.math.BigDecimal;

class FloatingPointExample {
    public static void main(String[] args) {
        // Prints 7.6000004
        System.out.println(8.6f - 1.0f);

        // Prints 7.6
        System.out.println(new BigDecimal("8.6").subtract(new BigDecimal("1.0")));

        // Do NOT pass floats to BigDecimal
        // Prints 7.6000003814697265625
        System.out.println(new BigDecimal(8.6f).subtract(new BigDecimal(1.0f)));

        // Do NOT pass doubles to BigDecimal
        // Prints 7.5999999999999996447286321199499070644378662109375
        System.out.println(new BigDecimal(8.6).subtract(new BigDecimal(1.0)));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...