+ 10

In JAVA , why does Imaginary number ( taking square root of a negative number ) and division by zero give no error ?

In JAVA , The code : System.out.println(Math.sqrt(-16.0)); will print : NaN . Similarly if we compile : System.out.println(0.0/0.0) ; , it will give the same output . Now change the numerator and compile : System.out.println(17.0/0.0); , it will give the output : Infinity . The same thing gives an error when we perform the operations on an Integer . The best part is trying to compile : System.out.println(Math.sqrt(-0.0)); , it will give -0.0 as the output . How can such weird outputs be explained logically ?

19th Apr 2019, 9:04 AM
Jishnu Mukherjee
Jishnu Mukherjee - avatar
2 Respuestas
+ 22
Might such output can be explained logically, here are some points which can help : ● domain for sqrt funcn is R+ U {0}, so taking sqrt of negative number will give NAN. ● 0/0 is indeterminate form, as upper 0 want to take value to 0 & lower zero want to take value to ○○, so it gives NAN here also. ● see syntax for Math.sqrt() , we pass double type in it (not integer) ● output for 17.0/0.0 is quite understable & for -0.0 it will be taken as 0.0 only (return type of Math.sqrt() function is also double) //for java
19th Apr 2019, 12:13 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
It's up to each programming language how to implement divisions by zero etc. Some might throw an error, others may get results like NaN or infinity. There's not the one correct way that is valid for all programming languages
19th Apr 2019, 9:58 AM
Anna
Anna - avatar