FORTRAN中的参数(常数)变量具有NaN值 [英] Having parameter (constant) variable with NaN value in FORTRAN
问题描述
是否可以使用NaN设置参数变量?并在特定的模块中具有该功能。我想用它来初始化其他一些变量。因此,如果它们没有更新,我将面临运行时错误,而不是模拟运行一些随机数。
我正在使用GFORTRAN。
这是可能的。您首先必须找出哪个位模式表示可能的NaN值之一。您可以将位模式存储为整数:
use,intrinsic :: iso_fortran_env
real(real64)x
integer(int64)i
x = 0
x = 0 / x
print *,x
print *,transfer(x,i)
end
它给出:-2251799813685248
然后你可以使用
real(real64),参数:: nan64 = transfer(-2251799813685248_int64,1._real64)$ b $初始化变量b
类似地,对于32位变量,您将得到整数-4194304,以便您可以执行
real(real32),parameter :: nan32 = transfer(-4194304_int32,1._real32)
许多编译器都可以为您选择为所有实际变量执行此操作。正如francescalus所显示的,在gfortran中它是 -finit-real = nan
。这样做手动为您提供更好的控制。
免责声明:切换到其他平台时要小心。排列顺序和其他问题可能会发挥作用,尽管我认为它确实可以。我假设符合IEEE标准的CPU。
请参阅francescalus对使用标准函数的替代方法的回答。不幸的是,它不适用于参数
常量,但是很有用。
Is it possible to set a parameter variable with NaN? and have that in a particular module. I want to use it for initialization of some other variables. Therefore, I'll be faced with a run-time error, if they are not updated, rather than simulations running with some random numbers. I am using GFORTRAN.
It is possible. You first have to find out which bit pattern represents one of the possible NaN values. You can store the bit pattern in an integer:
use, intrinsic :: iso_fortran_env
real(real64) x
integer(int64) i
x = 0
x = 0/x
print *, x
print *, transfer(x, i)
end
It gives: -2251799813685248
Then you can initialize your variables using
real(real64), parameter :: nan64 = transfer(-2251799813685248_int64, 1._real64)
Similarly for 32 bit variables you get the integer -4194304, so that you can do
real(real32), parameter :: nan32 = transfer(-4194304_int32, 1._real32)
Many compilers have an option to do that for you for all real variables. As francescalus shows, in gfortran it is -finit-real=nan
. Doing that manually gives you a finer control.
Disclaimer: Be careful when switching to a different platform. Endianness and other issues could play a role, even though I think it could be actually OK. I assumed an IEEE conforming CPU.
See, francescalus's answer for an alternative which uses a standard function. Unfortunately, it is not applicable for parameter
constants, but is useful.
这篇关于FORTRAN中的参数(常数)变量具有NaN值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!