next up previous contents
Next: Summation Formulas Up: Applications Part I. Previous: Applications Part I.   Contents

The Fibonacci Sequence

The Fibonacci sequence is defined by


One characteristic of the sequence is that the ratio tends to the Golden Ration


We want to write a program that computes the first 50 terms in the Fibonacci sequence; at each step we check whether the above ratio is sufficiently close to the Golden Ratio; and if it is, we print a message and end the computations.

The implementation follows.

PROGRAM fibonacci
!
  implicit none
  real :: x0=1.0, x1=1.0, x2
  real :: ratio, golden, tol=1.e-6
  integer :: i, n_max=50
!
  golden = (1.0+sqrt(5.0))/2.0
!  
  do i=2,n_max
    x2 = x0+x1
    print *,"x",i," = ",x2
    ratio = x2/x1 
    if ( abs(ratio-golden) .lt. tol ) then
      print *,"ratio did converge at i = ",i
      exit
    end if
    x0=x1; x1=x2
  end do
!
  if ( i .gt. n_max ) then
      print *,"ratio did not converge, i = ",i
  end if
!
end program fibonacci

During each sweep through the DO loop we compute and print the new element in the sequence, x2. Then, we calculate the x2/x1 ratio, and compare it to the golden ration; if they are suffieciently close we exit the loop. If the loop is terminated normally, the counter is n_max+1, and in this case the ratio did not converge. At the end of each sweep we prepare for the next iteration by assigning x1, x2 to x0,x1).



Adrian Sandu 2001-08-26