是否可以用 NaN 设置参数变量?并将其放在特定模块中.我想用它来初始化其他一些变量.因此,如果它们没有更新,我将面临运行时错误,而不是使用一些随机数运行的模拟.我正在使用 GFORTRAN.
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.
推荐答案有可能.您首先必须找出哪个位模式代表可能的 NaN 值之一.您可以将位模式存储为整数:
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它给出:-2251799813685248
It gives: -2251799813685248
然后你可以使用初始化你的变量
Then you can initialize your variables using
real(real64), parameter :: nan64 = transfer(-2251799813685248_int64, 1._real64)同样对于 32 位变量,你会得到整数 -4194304,这样你就可以做到
Similarly for 32 bit variables you get the integer -4194304, so that you can do
real(real32), parameter :: nan32 = transfer(-4194304_int32, 1._real32)许多编译器都可以选择为所有实变量执行此操作.正如 francescalus 所示,在 gfortran 中它是 -finit-real=nan.手动执行此操作可为您提供更好的控制.
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.
免责声明:切换到其他平台时要小心.字节序和其他问题可能会起作用,尽管我认为它实际上可能没问题.我假设一个符合 IEEE 标准的 CPU.
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.
请参阅 francescalus 对使用标准函数的替代方案的回答.不幸的是,它不适用于 parameter 常量,但很有用.
See, francescalus's answer for an alternative which uses a standard function. Unfortunately, it is not applicable for parameter constants, but is useful.