chap04/sample3.f90

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

 1program sample
 2  implicit none
 3
 4  real(8), parameter :: tolerance = 1.0e-8_8
 5
 6  real(8) :: x, sqrt_x0, sqrt_x1
 7
 8  write(*, *) 'Input a positive real number :'
 9  read(*, *) x
10
11  if(x < 0.0_8) then
12    write(*, *) 'Error: input must be a positive value'
13    stop
14  endif
15
16  ! 初期値
17  sqrt_x0 = 1.0_8
18  sqrt_x1 = x
19
20  !
21  ! 逐次近似によって平方根を求める
22  !
23  do while(abs((sqrt_x0 - sqrt_x1) / sqrt_x0) > tolerance)
24    sqrt_x0 = (sqrt_x0 + sqrt_x1) * 0.5_8
25    sqrt_x1 = x / sqrt_x0
26  enddo
27
28  ! 結果を表示
29  write(*, *) 'approx. = ', sqrt_x1
30  write(*, *) 'sqrt(x) = ', sqrt(x)
31  write(*, *) 'error   = ', abs(1 - sqrt_x1 / sqrt(x))
32
33  stop
34endprogram sample