The Fibonacci sequence is defined by
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).