NaN issue in fortran 90

32,546

NaN signifies not a number, and since there are many, different, reasons a calculation could give that result, they generally do not compare as equal against themselves. If you want to do nan-testing, fortran compilers that support the f2003 standard (which is recent versions of most compilers) have ieee_is_nan in the ieee_arithmetic module:

program testnan
    use ieee_arithmetic

    real (kind=kind(0.d0)) :: x,y,z

    x = sqrt(-1.d0)
    y = sqrt(-1.d0)
    z = 1.d0

    if ( ieee_is_nan(x) ) then
       write(*,*) 'X is NaN'
    endif
    if ( ieee_is_nan(y) ) then
       write(*,*) 'Y is NaN'
    endif
    if ( ieee_is_nan(x) .and. ieee_is_nan(y) ) then
       write(*,*) 'X and Y are NaN'
    endif

    if ( ieee_is_nan(z) ) then
       write(*,*) 'Z is NaN, too'
    else
       write(*,*) 'Z is a number'
    endif

end program testnan

Compiling and running this program gives

ifort -o nan nan.f90

 X is NaN
 Y is NaN
 X and Y are NaN
 Z is a number

Unfortunately, gfortran still doesn't implement ieee_arithmetic as time of writing, so with gfortran you have to use the non-standard isnan.

Share:
32,546

Related videos on Youtube

JoeCoolman
Author by

JoeCoolman

Updated on July 09, 2022

Comments

  • JoeCoolman
    JoeCoolman almost 2 years

    I realize that if you write

        Real (Kind(0.d0))::x,y
        x = sqrt(-1.d0)
        y = sqrt(-1.d0)
        if (x == y) then
           write(*,*)'yep, they are equals', x
        endif
    

    It compiles ok using ifort. But nothing is written, the conditional is always false, did you notice that? why is this so?

    • Kyle Kanos
      Kyle Kanos almost 11 years
      @JoeCoolman: This is an IEEE issue, not a Fortran issue, so Matlab will likely produce the same results as the Fortran code.
  • JoeCoolman
    JoeCoolman almost 11 years
    Excellent contributions of you all, I've learnt something new today.
  • Kyle Kanos
    Kyle Kanos almost 11 years
    I usually use if(x /= x) as my NaN-check in place of isnan and ieee_is_nan calls. Just another option, I suppose.