fortran - 无法使用通常的自等式来识别 nvfortran 中的 nan

标签 fortran nan nvidia

在大多数 fortran 编译器中,例如 gfortran,为了识别小的旧 nan,您可以利用 nan 不是自等价这一事实,通过进行某种等价性测试来进行检查。例如,如果 nanny=nan,则 (nanny/=nanny) 应输出 T。因此,对于以下代码:

program test_nan
implicit none

real :: nanny,zero=0.0


nanny=zero/zero
print*,nanny

if (nanny/=nanny) then
    print*,"found by self-equivalency"
else
    print*,"not found by self-equivalency"
end if

if (nanny-1==nanny) then
    print*,"found by perpetual transigence"
else
    print*,"not found by perpetual transigence"
end if
    
if (nanny>1000000000000.0) then
    print*,"found by big number"
else
    print*,"not found by big number"
end if

end program

如果我在 gfortran 中编译它并运行,我会得到:

              NaN
 found by self-equivalency
 not found by perpetual transigence
 not found by big number

但是,对 nvfortran 执行相同的操作会给出:

             NaN
 not found by self-equivalency
 not found by perpetual transigence
 not found by big number

nvfortran 中有没有办法可以检查 nan?

最佳答案

自 Fortran 2003 起,测试 NaN 的标准方法是通过该语言提供的 IEEE 754-1985 支持。下面是一个例子。请注意,测试变量与其自身是否相等并不是一个好主意,因为优化器通常会删除它 - 这可能就是您在上面看到的内容。除以零还会产生实现定义的行为,因此在那之后任何事情都可能发生 - 下面的代码显示了生成 NaN 的标准方法。

ijb@ijb-Latitude-5410:~/work/stack$ cat nan.f90
program test_nan

  Use, Intrinsic :: ieee_arithmetic, Only : ieee_signaling_nan, &
       ieee_support_nan, ieee_value, ieee_is_nan

  implicit none

  real :: nanny

  If( .Not. ieee_support_nan( nanny ) ) Then
     Write( *, * ) 'Processor does not support NaNs'
     Stop
  End If

  nanny = ieee_value( nanny, ieee_signaling_nan )
  If( ieee_is_nan( nanny ) ) Then
     Write( *, * ) 'Nanny is a Nan'
  Else
     Write( *, * ) 'Nanny is NOT a Nan, she is ', nanny
  End If

  nanny = 3.0
  If( ieee_is_nan( nanny ) ) Then
     Write( *, * ) 'Nanny is a Nan'
  Else
     Write( *, * ) 'Nanny is NOT a Nan, she is ', nanny
  End If

end program test_nan
ijb@ijb-Latitude-5410:~/work/stack$ gfortran --version
GNU Fortran (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

ijb@ijb-Latitude-5410:~/work/stack$ gfortran -std=f2018 -Wall -Wextra -fcheck=all -O -Wuse-without-only nan.f90 -o nan
ijb@ijb-Latitude-5410:~/work/stack$ ./nan
 Nanny is a Nan
 Nanny is NOT a Nan, she is    3.00000000    
ijb@ijb-Latitude-5410:~/work/stack$ 

关于fortran - 无法使用通常的自等式来识别 nvfortran 中的 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67659946/

相关文章:

pandas - 如何确定 Pandas 中非 NaN 系列的结尾

Javascript 形式 NAN 错误

Javascript:Math.min() 返回 NaN

cuda - 我可以使用 Quadro K4000 和 K2000 进行 GPUDirect v2 点对点 (P2P) 通信吗?

python - fatal error : cuda_runtime_api. h:尝试在 docker 中使用 cuda 时没有这样的文件或目录

fortran - Fortran、Cobol、Basic 和 Forth 是高级编程语言吗?

interface - 如何在 Fortran 界面中使用用户定义类型

linux - Nvidia-docker 将文件夹添加到容器

oop - 如何在子模块 Fortran 中使用类型

fortran - 意图(out)和意图(inout)之间的区别