chap04/kadai5.f90

サンプルコードのダウンロード

 1program answer
 2  implicit none
 3
 4  logical :: status
 5  integer :: i, n, m
 6  real(8) :: epsilon, e, c, etrue, error
 7
 8  read(*, *) n
 9
10  if(n <= 1) then
11    write(*, *) 'Number of terms must be greater than 1'
12    stop
13  endif
14
15  read(*, *) epsilon
16
17  if(epsilon < 0.0_8 .or. epsilon > 1.0_8) then
18    write(*, *) 'Tolerance must be in a range 0 < epsilon < 1'
19    stop
20  endif
21
22  status = .false.
23  etrue = exp(1.0_8)
24  e = 1.0_8
25  c = 1.0_8
26  m = n
27  do i = 1, n
28    c = c / i
29    e = e + c
30    error = abs(e - etrue) / etrue
31    if(error < epsilon) then
32      status = .true.
33      m = i
34      exit
35    endif
36  enddo
37
38  if(status) then
39    write(*, *) 'Converged !'
40  else
41    write(*, *) 'Did not converge !'
42  endif
43
44  write(*, *) 'N                  : ', m
45  write(*, *) 'Exact value        : ', etrue
46  write(*, *) 'Approximated value : ', e
47  write(*, *) 'Error              : ', error
48
49  stop
50endprogram answer