📅  最后修改于: 2020-11-04 06:21:56             🧑  作者: Mango
我们已经讨论过,在旧版本的Fortran中,有两种实类型:默认实类型和双精度类型。
但是,Fortran 90/95通过种类说明提供了对实数和整数数据类型的精度的更多控制。
不同种类的数字在计算机内部的存储方式不同。 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
Fortran提供了两个更多的内在函数来获取种类值,以获取整数和实数所需的精度-
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