Что такое nan java
Перейти к содержимому

Что такое nan java

  • автор:

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?

4,108 3 3 gold badges 29 29 silver badges 55 55 bronze badges
asked Apr 11, 2010 at 17:57
14.7k 35 35 gold badges 80 80 silver badges 109 109 bronze badges

There is a good description of NaN and of the common pitfalls when using NaN in Java: ppkwok.blogspot.co.uk/2012/11/…

Nov 25, 2012 at 1:56

If you are asking «what good is NaN?» in Java (or any other language), I can give you a use case where it is very handy: when I have a 2-D array of floats, but my calculation has no meaningful value for some portion of that 2-D array, I’ll fill that value with «NaN». This can be used to signal downstream users of my calculation (such as when it is turned into a raster image) «don’t pay attention to the value at this point». Very useful!

Jun 6, 2018 at 13:36
BTW, what — exactly — does it mean to «shrink» a double? Curious.
Jun 6, 2018 at 13:38

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.

5,093 5 5 gold badges 40 40 silver badges 64 64 bronze badges
answered Apr 11, 2010 at 18:00
KennyDeriemaeker KennyDeriemaeker
2,211 1 1 gold badge 17 17 silver badges 16 16 bronze badges

Additionally, NaN is defined by The IEEE Standard for Floating-Point Arithmetic (IEEE 754) quite explicitly which Java follows blindly. Reading the standard opens your eyes to a lot of things, the multiple values of zero being one of the things.

Apr 11, 2010 at 18:57

Also, NaN has the interesting property of being the only «number» which is not the same as itself when compared. Therefore a common (and in many languages the only) test if a number x is NaN is the following: boolean isNaN(x)

Mar 18, 2013 at 18:19

. «Taking square root of negative number is undefined (in arithmetics)». Its not! its actually i and some languages like python deal very well with it. It may be not the case in java thou

Feb 10, 2014 at 18:40

@RafaelT I’d say it is undefined in non-complex arithmetic. There is no way to assign a complex number to a float or double in Java. Python is dynamically typed, therefore it may be possibly to just return a complex number in this case.

Mar 27, 2014 at 13:11
@sstn agreed, although if it’s a complex number then it’s definitely not not a number 🙂
May 13, 2014 at 14:55

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.

answered Apr 11, 2010 at 18:01
380k 78 78 gold badges 576 576 silver badges 618 618 bronze badges
Converting how? With parseFloat() or parseDouble ? Or something else?
Mar 19, 2020 at 17:16

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).

answered Apr 11, 2010 at 17:59
367k 55 55 gold badges 678 678 silver badges 679 679 bronze badges

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 .

import java.lang.Float; import java.lang.Math; public class Nan < public static void main(String[] args) < // Generate some NaNs. float nan = Float.NaN; float zero_div_zero = 0.0f / 0.0f; float sqrt_negative = (float)Math.sqrt(-1.0); float log_negative = (float)Math.log(-1.0); float inf_minus_inf = Float.POSITIVE_INFINITY - Float.POSITIVE_INFINITY; float inf_times_zero = Float.POSITIVE_INFINITY * 0.0f; float quiet_nan1 = Float.intBitsToFloat(0x7fc00001); float quiet_nan2 = Float.intBitsToFloat(0x7fc00002); float signaling_nan1 = Float.intBitsToFloat(0x7fa00001); float signaling_nan2 = Float.intBitsToFloat(0x7fa00002); float nan_minus = -nan; // Generate some infinities. float positive_inf = Float.POSITIVE_INFINITY; float negative_inf = Float.NEGATIVE_INFINITY; float one_div_zero = 1.0f / 0.0f; float log_zero = (float)Math.log(0.0); // Double check that they are actually NaNs. assert Float.isNaN(nan); assert Float.isNaN(zero_div_zero); assert Float.isNaN(sqrt_negative); assert Float.isNaN(inf_minus_inf); assert Float.isNaN(inf_times_zero); assert Float.isNaN(quiet_nan1); assert Float.isNaN(quiet_nan2); assert Float.isNaN(signaling_nan1); assert Float.isNaN(signaling_nan2); assert Float.isNaN(nan_minus); assert Float.isNaN(log_negative); // Double check that they are infinities. assert Float.isInfinite(positive_inf); assert Float.isInfinite(negative_inf); assert !Float.isNaN(positive_inf); assert !Float.isNaN(negative_inf); assert one_div_zero == positive_inf; assert log_zero == negative_inf; // Double check infinities. // See what they look like. System.out.printf("nan 0x%08x %f\n", Float.floatToRawIntBits(nan ), nan ); System.out.printf("zero_div_zero 0x%08x %f\n", Float.floatToRawIntBits(zero_div_zero ), zero_div_zero ); System.out.printf("sqrt_negative 0x%08x %f\n", Float.floatToRawIntBits(sqrt_negative ), sqrt_negative ); System.out.printf("log_negative 0x%08x %f\n", Float.floatToRawIntBits(log_negative ), log_negative ); System.out.printf("inf_minus_inf 0x%08x %f\n", Float.floatToRawIntBits(inf_minus_inf ), inf_minus_inf ); System.out.printf("inf_times_zero 0x%08x %f\n", Float.floatToRawIntBits(inf_times_zero), inf_times_zero); System.out.printf("quiet_nan1 0x%08x %f\n", Float.floatToRawIntBits(quiet_nan1 ), quiet_nan1 ); System.out.printf("quiet_nan2 0x%08x %f\n", Float.floatToRawIntBits(quiet_nan2 ), quiet_nan2 ); System.out.printf("signaling_nan1 0x%08x %f\n", Float.floatToRawIntBits(signaling_nan1), signaling_nan1); System.out.printf("signaling_nan2 0x%08x %f\n", Float.floatToRawIntBits(signaling_nan2), signaling_nan2); System.out.printf("nan_minus 0x%08x %f\n", Float.floatToRawIntBits(nan_minus ), nan_minus ); System.out.printf("positive_inf 0x%08x %f\n", Float.floatToRawIntBits(positive_inf ), positive_inf ); System.out.printf("negative_inf 0x%08x %f\n", Float.floatToRawIntBits(negative_inf ), negative_inf ); System.out.printf("one_div_zero 0x%08x %f\n", Float.floatToRawIntBits(one_div_zero ), one_div_zero ); System.out.printf("log_zero 0x%08x %f\n", Float.floatToRawIntBits(log_zero ), log_zero ); // NaN comparisons always fail. // Therefore, all tests that we will do afterwards will be just isNaN. assert !(1.0f < nan); assert !(1.0f == nan); assert !(1.0f >nan); assert !(nan == nan); // NaN propagate through most operations. assert Float.isNaN(nan + 1.0f); assert Float.isNaN(1.0f + nan); assert Float.isNaN(nan + nan); assert Float.isNaN(nan / 1.0f); assert Float.isNaN(1.0f / nan); assert Float.isNaN((float)Math.sqrt((double)nan)); > > 
javac Nan.java && java -ea Nan 
nan 0x7fc00000 NaN zero_div_zero 0x7fc00000 NaN sqrt_negative 0xffc00000 NaN log_negative 0xffc00000 NaN inf_minus_inf 0x7fc00000 NaN inf_times_zero 0x7fc00000 NaN quiet_nan1 0x7fc00001 NaN quiet_nan2 0x7fc00002 NaN signaling_nan1 0x7fa00001 NaN signaling_nan2 0x7fa00002 NaN nan_minus 0xffc00000 NaN positive_inf 0x7f800000 Infinity negative_inf 0xff800000 -Infinity one_div_zero 0x7f800000 Infinity log_zero 0xff800000 -Infinity 

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»?

    • 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.

    nan = 0x7fc00000 = 0 11111111 10000000000000000000000 positive_inf = 0x7f800000 = 0 11111111 00000000000000000000000 negative_inf = 0xff800000 = 1 11111111 00000000000000000000000 | | | | | mantissa | exponent | sign 
    • 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

    Tested in Ubuntu 18.10 amd64, OpenJDK 1.8.0_191.

    NaN (Not a Number) in Java

    Yes, You guessed it right: ArithmeticException
    Output:

    Exception in thread "main" java.lang.ArithmeticException: / by zero at traps.Test.main(Test.java:3)

    Now guess the Output of :

    public class Test
    public static void main(String[] args)
    System.out.println( 2.0 % 0 );

    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.

    //Java Program to illustrate NaN
    public class Test
    public static void main(String[] args)
    System.out.println( 2.0 % 0 );
    System.out.println( 0.0 / 0 );
    System.out.println(Math.sqrt(- 1 ));

    NaN NaN NaN

    In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.

    public static final float NaN = 0f / 0f; public static final double NaN = 0d / 0d;

    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)

    // Java program to test relational operator on NaN
    public class ComparingNaN
    public static void main(String[] args)
    // comparing NaN constant field defined in
    // Float Class
    System.out.print( «Check if equal :» );
    System.out.println(Float.NaN == Float.NaN);
    System.out.print( «Check if UNequal: » );
    System.out.println(Float.NaN != Float.NaN);
    // comparing NaN constant field defined in Double Class
    System.out.print( «Check if equal: » );
    System.out.println(Double.NaN == Double.NaN);
    System.out.print( «Check if UNequal: » );
    System.out.println(Double.NaN != Double.NaN);
    // More Examples
    double NaN = 2.1 % 0 ;
    System.out.println(( 2.1 % 0 ) == NaN);
    System.out.println(NaN == NaN);

    Check if equal :false Check if UNequal: true Check if equal: false Check if UNequal: true false false

    isNaN() method

    This method returns true if the value represented by this object is NaN; false otherwise.

    import java.lang.*;
    public class isNan
    public static void main(String[] args)
    Double x = new Double(- 2.0 / 0.0 );
    Double y = new Double( 0.0 / 0.0 );
    // returns false if this Double value is not a Not-a-Number (NaN)
    System.out.println(y + » plain»>+ y.isNaN());
    // returns true if this Double value is a Not-a-Number (NaN)
    System.out.println(x + » plain»>+ x.isNaN());

    NaN = true -Infinity = false

    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).

    // Java program to illustrate output of floating
    // point number operations
    public class Test
    public static void main(String[] args)
    System.out.println( 2.0 / 0 );
    System.out.println(- 2.0 / 0 );
    System.out.println( 9 .0E234 / 0 .1E- 234 );

    Infinity -Infinity Infinity

    Like Article
    Suggest improvement
    Share your thoughts in the comments
    Add Your Comment

    Please Login to comment.

    Similar Reads

    Java Program to Check If a Number is Neon Number or Not
    Java Program to Check If a Number is Spy number or not

    Java Program for Check whether all the rotations of a given number is greater than or equal to the given number or not

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *