!======================================================================!
!Progaram to find solutions to equations of the form f(x)=0 using
!bisection method (Bolanzo method)
!LANGUAGE :: FORTRAN 95 (compiler: G95 Fortran Compiler) !
!======================================================================!
PROGRAM bisection
IMPLICIT NONE
REAL :: xL,xH,tolerance,d,xMid
INTEGER :: iterations = 0
WRITE (*,*) 'Enter the two numbers between which root is to be found'
READ (*,*) xL,xH
WRITE (*,*) 'The root should be correct upto how many decimal places?'
READ (*,*) tolerance
IF ((f(xL)*f(xH))== 0) THEN
IF ((f(xL)==0).AND.(f(xH)==0)) THEN
WRITE (*,*) 'The desired roots are',xL,' and ',xH,' themselves'
ELSE IF (f(xL)==0) THEN
WRITE (*,*) 'The desired root is',xL
ELSE IF (f(xH)==0) THEN
WRITE (*,*) 'The desired root is',xH
END IF
ELSE IF ((f(xL)*f(xH))>0) THEN
WRITE (*,*) 'The root does not lie between ',xL,' and ',xH
ELSE IF ((f(xL)*f(xH))<0) THEN
DO
xMid=(xL+xH)/2
IF (f(xMid)==0) EXIT
d=ABS((xMid-xL)/xMid)
IF (d<((0.1)**tolerance)) EXIT !accuracy
IF ((f(xMid)*f(xL))<0) THEN !root lies between xMid and xL
xH=xL
xL=xMid
!PRINT 10,xL,xH,d,'g'
!10 FORMAT (F12.7,3X,F12.7,3X,F12.7,3X,A2)
ELSE IF ((f(xMid)*f(xH))<0) THEN !root lies between xMid and xH
xL=xMid
xH=xH
END IF
iterations = iterations + 1
END DO
WRITE (*,*) 'The root is',xMid
WRITE (*,*) 'Total iterations =',iterations
END IF
CONTAINS
FUNCTION f(y)
REAL :: f
REAL,INTENT (IN)::y
f=y*EXP(y)-1
END FUNCTION f
END PROGRAM
!-------------------------OUTPUT-----------------------------!
! Enter the two numbers between which root is to be found !
! 0.1 !
! 0.9 !
! The root should be correct upto how many decimal places? !
! 6 !
! The root is 0.56714296 !
! Total iterations = 20 !
!------------------------------------------------------------!