# Fortran數字精度

## 類型屬性

real, kind = 2 :: a, b, c
real, kind = 4 :: e, f, g
integer, kind = 2 :: i, j, k
integer, kind = 3 :: 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

## 查詢變量的大小

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_int_kind (r)
• selected_real_kind ([p, r])

selected_real_kind函數返回一個整數，一個給定的小數精度p 和十進制指數範圍r 的類型的參數值。小數精度是明顯的位數，而小數指數範圍規定的最小和最大可表示數。因此該範圍是從10-r 到 10+r。

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