Java – why is the last number wrong?

Why output the last numeric error code:

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello world");
        System.out.println("I wounder is the sqaure root of (2*3) the 
                           same as the sqaure root of 2 and 3 multiplied.");
        double squareroot0 = Math.pow(3*2,0.5);
        double squarroot1 = (Math.pow(3,0.5) * Math.pow(2,0.5)); 
        System.out.println("So is it the same?");

        System.out.println("is " + squareroot0 + " the equvielant of " + 
                                               squarroot1 + "?");
        if(squareroot0 == squarroot1) {
            System.out.println("Yes number one and number two are 
                                               the same,Congrats!");
        }else {
            System.out.println("No they are not! ");
        }

        System.out.println(squareroot0);
        System.out.println(squarroot1);


    }
}

Output:

Hello world
I wonder is the sqaure root of (2*3) the same as the sqaure 
root of 2 and 3 multiplied.
So is it the same?
is 2.449489742783178 the equvielant of 2.4494897427831783?
No they are not! 
2.449489742783178
2.4494897427831783

They are equal in mathematics. What's going on?

Math. Sqrt() and math Pow (, 0.5) is equally accurate

Solution

In a limited computer, you can't represent numbers with infinite precision, so you need reincarnation What you see is the effect of rounding This is inherent in all uses of floating - point numbers

Mandatory link: what every computer scientist should know about floating point arithmetic

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
分享
二维码
< <上一篇
下一篇>>