-1

I'm doing the past paper of Java to prepare my Java examination.

A question in paper is giving some java code to you, and you need to evaluate the value & type of it, or find does it have any compilation error or runtime error.

Here is a code :

Math.sqrt(-2.0)

I try it in my java, but it only show NaN , and no error message was show.

So, should I write it is runtime error or just write NaN in the value?

BudwiseЯ
  • 1,846
  • 2
  • 16
  • 28
Tom Fong
  • 97
  • 2
  • 6

3 Answers3

0

NaN means "not a number", and you got it because regular floating-point math doesn't support imaginary numbers. It's a placeholder that means "invalid value", but it's not an error at the language level.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

It's not an error or exception. You can just consider it as a value of the result.

南山怀槿
  • 71
  • 1
  • 6
0

No, The result you are getting is not a error at all. Function is returning value NaN means Not a Number

.

This function executes some underlying system algorithm and return value NaN.

To help ensure portability of Java programs, the definitions of some of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic.

Please refer this answer for more details.

About

So, should I write it is runtime error or just write NaN in the value?

It's up to you or requirement. If you are using this value in further calculations you should handle this case very carefully. May be return zero if NaN could be a solution.

Community
  • 1
  • 1
Umesh Aawte
  • 4,590
  • 7
  • 41
  • 51