[英]Maximum value of 64 bit floating point number for overflow detection
I have a seemingly simple problem: I want to detect whether a floating point addition in Fortran will overflow by doing something like the following:我有一个看似简单的问题:我想通过执行以下操作来检测 Fortran 中的浮点加法是否会溢出:
real*8 :: a, b, c
a = ! some value
b = ! some value
if (b > DOUBLE_MAX - a) then
! handle overflow
else
c = a + b
The problem is that I don't know what DOUBLE_MAX
should be.问题是我不知道
DOUBLE_MAX
应该是什么。 I'm aware of how floating point numbers are represented according to IEEE 754 but the largest value representable by a double precision floating point number seems to be too large for a variable of type real*8
(ie if I try to assign 1.7976931348623157e+308
to such a variable gfortran complains).我知道如何根据 IEEE 754 来表示浮点数,但是双精度浮点数可表示的最大值对于
real*8
类型的变量来说似乎太大了(即,如果我尝试分配1.7976931348623157e+308
到这样一个变量 gfortran 抱怨)。 C and C++ have predefined constants/generic functions for this purpose but I couldn't find a Fortran equivalent.为此,C 和 C++ 具有预定义的常量/通用函数,但我找不到 Fortran 等效项。
Note: I'm aware that real*8
is not really part of the standard but there seems to be no other way to reliably specify that a floating point number should use the double precision format.注意:我知道
real*8
并不是标准的真正组成部分,但似乎没有其他方法可以可靠地指定浮点数应使用双精度格式。
Something like this?像这样的东西?
real(REAL64) function func( a, b )
use, intrinsic :: iso_fortran_env, only: REAL64, INT64
use, intrinsic :: ieee_arithmetic, only: ieee_value, ieee_set_flag, IEEE_OVERFLOW, IEEE_QUIET_NAN
implicit none
real(REAL64), intent(in) :: a, b
real(REAL64), parameter :: MAX64 = huge(0.0_REAL64)
if ( b > MAX64-a ) then
! Set IEEE_OVERFLOW flag and return NaN
call ieee_set_flag(IEEE_OVERFLOW,.true.)
func = ieee_value(func,IEEE_QUIET_NAN)
else
func = a + b
end if
return
end function func
All I could find for intrinsic ieee_exceptions
module is:我能找到的内在
ieee_exceptions
模块是:
https://github.com/gcc-mirror/gcc/blob/master/libgfortran/ieee/ieee_exceptions.F90 https://github.com/gcc-mirror/gcc/blob/master/libgfortran/ieee/ieee_exceptions.F90
There are likely better ways to detect overflow, but the precise answer to your question is to use the huge
function.可能有更好的方法来检测溢出,但您问题的准确答案是使用
huge
函数。 HUGE(a)
returns the largest possible number representable by the type a
. HUGE(a)
返回类型a
表示的最大可能数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.