-1

I wrote a program which i suppose should print true , Instead its giving false as out put.

  public class Test {
  public static void main(String[] args) {
    double i = 0.0 / 0.0;
    System.out.println(i - i == 0);
 }
}

Can some one explain me why it is behaving so .

T-Bag
  • 10,916
  • 3
  • 54
  • 118

5 Answers5

2

It is because i = 0.0 / 0.0 is equal to NaN, so NaN neither equal to 0 nor to it self (Nan)

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
1

This is because :

public class TestClass {
    public static void main(String[] args) {
    double i = 0.0 / 0.0;
    System.out.println(i-i); //NaN
    System.out.println(i - i == 0);//false
 }
}

NaN, standing for not a number, is a numeric data type value representing an undefined or unrepresentable value, especially in floating-point calculations.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0
double i = 0.0 / 0.0; // this assigned i=NaN

"NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.

when you compare

 System.out.println(i - i == 0); // it do Nan-Nan which is NaN

It try to compare

 NaN to 0 which is false

Java Floating Points

bNd
  • 7,512
  • 7
  • 39
  • 72
0
double i = 0.0 / 0.0;

It will evaluate to NaN

And i - i will be NaN - NaN Which is again NaN i.e. != 0

afzalex
  • 8,598
  • 2
  • 34
  • 61
0

What were you expecting? 0.0 / 0.0 is an indeterminate form, which is mapped with a special value according to floating format which is NaN.

It's a special value because it's destructive, it propagates through each successive arithmetic operation, and that's good because it helps diagnosing problems with operations.

Indeed that's the case 0.0 / 0.0 = NaN and NaN - whatever = NaN (so (0.0/0.0)-5.0 yields NaN too).

Jack
  • 131,802
  • 30
  • 241
  • 343