fortran 90中的NaN问题 [英] NaN issue in fortran 90

查看:195
本文介绍了fortran 90中的NaN问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,如果你写

    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 ,您注意到了吗?为什么会这样?

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

推荐答案

NaN 表示不是数字,并且从那里开始有许多不同的原因可以使计算得出结果,它们通常不会与自己进行比较.如果要进行nan-testing,则支持f2003标准的fortran编译器(大多数编译器的最新版本)在ieee_is_nan > ieee_arithmetic 模块:

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

编译并运行该程序即可

ifort -o nan nan.f90

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.

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

这篇关于fortran 90中的NaN问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆