我意识到,如果你编写
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,你有注意到吗?为什么会这样呢?
我意识到,如果你编写
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,你有注意到吗?为什么会这样呢?
NaN代表非数字,由于可能有很多不同的原因导致计算结果为NaN,它们通常不会与自己相等。如果您想进行NaN测试,支持f2003标准(大多数编译器的最新版本)的Fortran编译器在ieee_arithmetic
模块中有ieee_is_nan
函数:
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
,因此您必须使用非标准的isnan
。
if(x /= x)
作为我的 NaN 检查,而不是调用 isnan
和 ieee_is_nan
方法。这只是另一种选择。 - Kyle Kanos
if(outcome == sqrt(-1.d0) then etc.
。好的@Jonathan Dursi,我大致阅读了您给我的链接(因为答案很长)。结论是要注意Fortran中的这些问题。对于Fortran来说,1.d0/0.d0等于2.d0/0.d0。我将在Matlab中测试它并查看其行为。 - JoeCoolmanuse ieee_arithmetic
并使用内置的IEEE_IS_NAN(X)
来检查NaN。 - Jonathan Dursi