Что такое nan java
Can You guess the output of following code fragment:
Yes, You guessed it right: ArithmeticException
Output:
Now guess the Output of :
Did you guessed it right ?
Output:
What is 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. Finding out the square root of a negative number too is undefined.
In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.
How to Compare NaN Values?
All numeric operations with NaN as an operand produce NaN as a result. Reason behind this is that NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false.
- The numerical comparison operators , and >= always return false if either or both operands are NaN.(§15.20.1)
- The equality operator == returns false if either operand is NaN.
- The inequality operator != returns true if either operand is NaN . (§15.21.1)
isNaN() method
This method returns true if the value represented by this object is NaN; false otherwise.
Floating type doesn’t produces Exception while operating with mathematical values
IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately.
Java is following known math facts. 1.0 / 0.0 is infinity, but the others are indeterminate forms, which Java represents as NaN (not a number).
This article is contributed by Pankaj kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Class Double
In addition, this class provides several methods for converting a double to a String and a String to a double , as well as other constants and methods useful when dealing with a double .
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Floating-point Equality, Equivalence, and Comparison
An equivalence relation on a set of values is a boolean relation on pairs of values that is reflexive, symmetric, and transitive. For more discussion of equivalence relations and object equality, see the Object.equals specification. An equivalence relation partitions the values it operates over into sets called equivalence classes. All the members of the equivalence class are equal to each other under the relation. An equivalence class may contain only a single member. At least for some purposes, all the members of an equivalence class are substitutable for each other. In particular, in a numeric expression equivalent values can be substituted for one another without changing the result of the expression, meaning changing the equivalence class of the result of the expression.
- If v1 and v2 are both NaN, then v1 == v2 has the value false . Therefore, for two NaN arguments the reflexive property of an equivalence relation is not satisfied by the == operator.
- If v1 represents +0.0 while v2 represents -0.0 , or vice versa, then v1 == v2 has the value true even though +0.0 and -0.0 are distinguishable under various floating-point operations. For example, 1.0/+0.0 evaluates to positive infinity while 1.0/-0.0 evaluates to negative infinity and positive infinity and negative infinity are neither equal to each other nor equivalent to each other. Thus, while a signed zero input most commonly determines the sign of a zero result, because of dividing by zero, +0.0 and -0.0 may not be substituted for each other in general. The sign of a zero input also has a non-substitutable effect on the result of some math library methods.
For ordered comparisons using the built-in comparison operators ( < , <= , etc.), NaN values have another anomalous situation: a NaN is neither less than, nor greater than, nor equal to any value, including itself. This means the trichotomy of comparison does not hold.
To provide the appropriate semantics for equals and compareTo methods, those methods cannot simply be wrappers around == or ordered comparison operations. Instead, equals defines NaN arguments to be equal to each other and defines +0.0 to not be equal to -0.0 , restoring reflexivity. For comparisons, compareTo defines a total order where -0.0 is less than +0.0 and where a NaN is equal to itself and considered greater than positive infinity.
The operational semantics of equals and compareTo are expressed in terms of bit-wise converting the floating-point values to integral values.
The natural ordering implemented by compareTo is consistent with equals. That is, two objects are reported as equal by equals if and only if compareTo on those objects returns zero.
The adjusted behaviors defined for equals and compareTo allow instances of wrapper classes to work properly with conventional data structures. For example, defining NaN values to be equals to one another allows NaN to be used as an element of a HashSet or as the key of a HashMap . Similarly, defining compareTo as a total ordering, including +0.0 , -0.0 , and NaN, allows instances of wrapper classes to be used as elements of a SortedSet or as keys of a SortedMap .
In Java, what does NaN mean?
I have a program that tries to shrink a double down to a desired number. The output I get is NaN .
What does NaN mean in Java?
![]()
11 Answers 11
«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.
![]()
NaN means “Not a Number” and is basically a representation of a special floating point value in the IEE 754 floating point standard. NaN generally means that the value is something that cannot be expressed with a valid floating point number.
A conversion will result in this value, when the value being converted is something else, for example when converting a string that does not represent a number.
NaN means «Not a Number» and is the result of undefined operations on floating point numbers like for example dividing zero by zero. (Note that while dividing a non-zero number by zero is also usually undefined in mathematics, it does not result in NaN but in positive or negative infinity).
Minimal runnable example
The first thing that you have to know, is that the concept of NaN is implemented directly on the CPU hardware.
All major modern CPUs seem to follow IEEE 754 which specifies floating point formats, and NaNs, which are just special float values, are part of that standard.
Therefore, the concept will be the very similar across any language, including Java which just emits floating point code directly to the CPU.
Before proceeding, you might want to first read up the following answers I’ve written:
- a quick refresher of the IEEE 754 floating point format: What is a subnormal floating point number?
- some lower level NaN basics covered using C / C++: What is difference between quiet NaN and signaling NaN?
Now for some Java action. Most of the functions of interest that are not in the core language live inside java.lang.Float .
So from this we learn a few things:
weird floating operations that don’t have any sensible result give NaN:
- 0.0f / 0.0f
- sqrt(-1.0f)
- log(-1.0f)
In C, it is actually possible to request signals to be raised on such operations with feenableexcept to detect them, but I don’t think it is exposed in Java: Why does integer division by zero 1/0 give error but floating point 1/0.0 returns "Inf"?
weird operations that are on the limit of either plus or minus infinity however do give +- infinity instead of NaN
- 1.0f / 0.0f
- log(0.0f)
0.0 almost falls in this category, but likely the problem is that it could either go to plus or minus infinity, so it was left as NaN.
if NaN is the input of a floating operation, the output also tends to be NaN
there are several possible values for NaN 0x7fc00000 , 0x7fc00001 , 0x7fc00002 , although x86_64 seems to generate only 0x7fc00000 .
NaN and infinity have similar binary representation.
Let’s break down a few of them:
From this we confirm what IEEE754 specifies:
- both NaN and infinities have exponent == 255 (all ones)
- infinities have mantissa == 0. There are therefore only two possible infinities: + and -, differentiated by the sign bit
- NaN has mantissa != 0. There are therefore several possibilities, except for mantissa == 0 which is infinity
NaNs can be either positive or negative (top bit), although it this has no effect on normal operations
NaN в Java
Проще говоря,NaN — это значение числового типа данных, которое означает «не число».
В этом кратком руководстве мы объясним значениеNaN в Java и различные операции, которые могут создавать или задействовать это значение.
2. Что такоеNaN?
NaN usually indicates the result of invalid operations. Например, попытка разделить ноль на ноль является одной из таких операций.
We also use NaN for unrepresentable values. Квадратный корень из -1 является одним из таких случаев, поскольку мы можем описать значение (i) только в комплексных числах.
IEEE Standard for Floating-Point Arithmetic (IEEE 754) определяет значениеNaN. In Java, the floating-point types float and double implement this standard.
«A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).”
«Константа, содержащая не-числовое (NaN) значение типа float. Это эквивалентно значению, возвращаемому Float.intBitsToFloat (0x7fc00000) ».
У нас нет такого типа констант для других числовых типов данных в Java.
3. Сравнение сNaN
При написании методов на Java, мы должны проверить, что ввод действителен и находится в ожидаемом диапазоне. ЗначениеNaN в большинстве случаев не является допустимым вводом. Следовательно, мы должны убедиться, что входное значение не является значениемNaN, и обработать эти входные значения соответствующим образом.
NaN нельзя сравнивать ни с одним значением плавающего типа. Это означает, что мы получимfalse для всех операций сравнения, включающихNaN (кроме «! =», Для которого мы получаемtrue).
Мы получаемtrue для «x != x” тогда и только тогда, когдаx равноNaN:.
Следовательно,we cannot check for NaN by comparing with NaN using “==” or “!= “.. На самом деле, нам редко следует использовать операторы «==» или «! =» С типамиfloat илиdouble.
Вместо этого мы можем использовать выражение «x ! = x».. Это выражение возвращает истину только дляNAN.
Мы также можем использовать методыFloat.isNaN иDouble.isNaN для проверки этих значений.. Это предпочтительный подход, поскольку он более читабелен и понятен:
4. Производство операцийNaN
Выполняя операции с типамиfloat иdouble, нам необходимо знать значенияNaN.
Some floating-point methods and operations produce NaN values instead of throwing an Exception. Нам может потребоваться явная обработка таких результатов.
Обычный случай, приводящий к нечисловым значениям, — этоmathematically undefined numerical operations:
Числовые операции, которые не приводят к действительным числам, также даютNaN:
Все числовые операции сNaN в качестве операнда в результате даютNaN:
Наконец, мы не можем присвоитьnull переменным типаdouble илиfloat. Вместо этого мы можем явно назначитьNaN таким переменным, чтобы указать отсутствующие или неизвестные значения:
5. Заключение
В этой статье мы обсудилиNaN и различные операции с ним. Мы также обсудили необходимость обработкиNaN при явном выполнении вычислений с плавающей запятой в Java.