Assignment3
!-----------------------------------------------------------------------------------------------------
! This Fortran program finds the root of a function f(x) = x^3 + 2x^2 + x + 1 using the Secant Method
! where limits is the number of iteration steps can be no-convergent when the initial value a and b
! are not so close.
! it will also display the number o iteration used for finding the solution.
!-----------------------------------------------------------------------------------------------------
PROGRAM SECANTMETHOD
IMPLICIT NONE
! Declare variables
REAL*8 ::a, b, eps, result
INTEGER :: iter = 0, limit
DO
! getting the value of a, b, eps, limits
PRINT *, "----------------------------------------------------------------------------"
PRINT *, "Please enter the value of a, b, eps and limit with spaces/commas"
READ *, a, b, eps, limit
IF (a .eq. 0 .and. b .eq. 0) THEN
PRINT *, "PROGRAM EXIT!!!"
EXIT
ELSE
! the secant method will the find the approximate root uses
! two intial values a and b which are "close" to the solution.
result = SECANT(a, b, eps, iter, limit)
PRINT *, "RESULT: ", result
END IF
END DO
CONTAINS
! this secant function finds the approximate root uses two intial value of a and b
! and each itteration step an approximation x to the solution determine by the
! secant line
REAL*8 FUNCTION SECANT(a, b, eps, iter, limit)
REAL*8 :: a, b, x
INTEGER :: counter = 0
REAL*8, INTENT (IN) :: eps
INTEGER, INTENT(IN) :: limit, iter
! if the absoulate difference is less than eps # EXIT
DO WHILE(abs(a - b) > eps)
counter = counter + 1
IF (limit .eq. counter) THEN
PRINT *, "Result Not Found!! "
PRINT *, "Number of tires: ", limit
PRINT *, "Last Result is: "
EXIT
END IF
IF ( f(b) .eq. f(a)) THEN
b = b + 1
END IF
! to find the x we have to draw a stright line betwen the a and b
x = b - ((b - a) * f(b)) / (f(b) - f(a))
a = b
b = x
END DO
IF (iter .lt. limit) THEN
PRINT *, "Number of tires: ", counter
END IF
SECANT = a
END FUNCTION SECANT
! the testing function is f(x) = x^3 + 2x^2 + x + 1
REAL*8 FUNCTION f(x)
REAL*8, INTENT(IN) :: x
f = (x * x * x) - (2 * x * x) + x + 1
END FUNCTION f
END PROGRAM SECANTMETHOD
PROGRAM expFunction1
IMPLICIT NONE
REAL :: x, y, z
! declare the value of the 2
x = -2.0
PRINT *, x, exp(x)
DO WHILE (x .lt. 6.25)
y = exp(x)
z = myexp(x)
PRINT "(1X, F7.3, 2F12.6, 2(1PE13.5))", x, y, z, y, z
x = x + 0.5
END DO
CONTAINS
REAL FUNCTION myexp(x)
REAL, INTENT(IN) :: x
REAL :: approx, sum, sum_prev, counter
approx = x
counter = 1.0
sum_prev = 0.0
sum = x
DO WHILE (sum .ne. sum_prev)
sum_prev = sum
counter = counter + 1.0
approx = -(approx * (x / counter))
sum = sum + approx
END DO
myexp = sum
END FUNCTION myexp
END PROGRAM expFunction1