Fortran - 数值精度
-
简述
我们已经讨论过,在旧版本的 Fortran 中,有两个realtypes:默认的real类型和double precision类型。但是,Fortran 90/95 通过kind指定。 -
kind 属性
不同类型的数字在计算机内部的存储方式不同。这kind属性允许您指定数字在内部的存储方式。例如,real, kind = 2 :: a, b, c real, kind = 4 :: e, f, g integer, kind = 2 :: i, j, k integer, kind = 3 :: l, m, n
在上述声明中,实变量 e、f 和 g 比实变量 a、b 和 c 具有更高的精度。与整数变量 i、j 和 k 相比,整数变量 l、m 和 n 可以存储更大的值并具有更多的位数用于存储。虽然这取决于机器。例子
program kindSpecifier implicit none real(kind = 4) :: a, b, c real(kind = 8) :: e, f, g integer(kind = 2) :: i, j, k integer(kind = 4) :: l, m, n integer :: kind_a, kind_i, kind_e, kind_l kind_a = kind(a) kind_i = kind(i) kind_e = kind(e) kind_l = kind(l) print *,'default kind for real is', kind_a print *,'default kind for int is', kind_i print *,'extended kind for real is', kind_e print *,'default kind for int is', kind_l end program kindSpecifier
当您编译并执行上述程序时,它会产生以下结果 -default kind for real is 4 default kind for int is 2 extended kind for real is 8 default kind for int is 4
-
查询变量的大小
有许多内在函数可以让您询问数字的大小。例如,bit_size(i)内在函数指定用于存储的位数。对于实数,precision(x)内在函数,返回精度的小数位数,而range(x)内在函数返回指数的十进制范围。例子
program getSize implicit none real (kind = 4) :: a real (kind = 8) :: b integer (kind = 2) :: i integer (kind = 4) :: j print *,'precision of real(4) =', precision(a) print *,'precision of real(8) =', precision(b) print *,'range of real(4) =', range(a) print *,'range of real(8) =', range(b) print *,'maximum exponent of real(4) =' , maxexponent(a) print *,'maximum exponent of real(8) =' , maxexponent(b) print *,'minimum exponent of real(4) =' , minexponent(a) print *,'minimum exponent of real(8) =' , minexponent(b) print *,'bits in integer(2) =' , bit_size(i) print *,'bits in integer(4) =' , bit_size(j) end program getSize
当您编译并执行上述程序时,它会产生以下结果 -precision of real(4) = 6 precision of real(8) = 15 range of real(4) = 37 range of real(8) = 307 maximum exponent of real(4) = 128 maximum exponent of real(8) = 1024 minimum exponent of real(4) = -125 minimum exponent of real(8) = -1021 bits in integer(2) = 16 bits in integer(4) = 32
-
获取 kind 值
Fortran 提供了另外两个内在函数来获得所需的整数和实数精度的类型值 -- selected_int_kind (r)
- selected_real_kind ([p, r])
selected_real_kind 函数返回一个整数,该整数是给定十进制精度 p 和十进制指数范围 r 所需的种类类型参数值。十进制精度是有效位数,十进制指数范围指定最小和最大可表示数字。因此范围是从 10-r 到 10+r。例如, selected_real_kind (p = 10, r = 99) 返回小数点后 10 位精度所需的种类值,范围至少为 10-99 到 10+99。例子
program getKind implicit none integer:: i i = selected_real_kind (p = 10, r = 99) print *,'selected_real_kind (p = 10, r = 99)', i end program getKind
当您编译并执行上述程序时,它会产生以下结果 -selected_real_kind (p = 10, r = 99) 8