Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why java does not compare accurately large value at its upper range?

for input value of x = 200000000 and y = 20000000000000000, x and y lines will hold equal values after input(x^2 will be equal to 2*y), but on comparing these it prints NO i.e. x==y is false.

public static void main (String[] args) throws java.lang.Exception
{
    Scanner scn = new Scanner(System.in);
    int t = scn.nextInt();
    Long x = (long)Math.pow(scn.nextLong(),2);
    Long y = 2*scn.nextLong();
    System.out.println((x==y)?"YES":"NO");
}

Meanwhile, if I

System.out.println((x-y==0)?"YES":"NO");

It prints YES.
So why it is happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem is auto boxing.

Long x = (long)Math.pow(scn.nextLong(),2);
Long y = 2*scn.nextLong();

x and y are Objects of type Long

either use Object equality test

System.out.println(x.equals(y)?"YES":"NO");

or use primitives

long x = (long)Math.pow(scn.nextLong(),2);
long y = 2*scn.nextLong();
System.out.println((x==y)?"YES":"NO");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading