5

我意识到如果你写

    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

它使用 ifort 编译正常。但是什么也没写,条件总是false,你注意到了吗?为什么会这样?

4

1 回答 1

16

NaN表示不是数字,并且由于计算可以得出该结果的原因有很多,因此它们通常不会与自己进行比较。如果要进行 nan-testing,支持 f2003 标准(大多数编译器的最新版本)的 fortran 编译器ieee_is_nanieee_arithmetic模块中有:

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

编译和运行这个程序给出

ifort -o nan nan.f90

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

不幸的是,gfortran 在撰写本文时仍未实现ieee_arithmetic,因此使用 gfortran 您必须使用非标准的isnan.

于 2013-06-28T14:07:53.373 回答