fork download
  1. real :: x0, x, tol, f, dfdx ,df_dx
  2. integer :: max_iter, iter
  3.  
  4. f(x) = x**3-8*x**2+7*x+32 !Equation to solve
  5. dfdx(x) = (f(x + h) - f(x - h)) / (2.0 * h) !Central Difference Method
  6.  
  7. ! Constants:-
  8. tol = 1.0e-6 ! Tolerance for convergence
  9. max_iter = 100 ! Maximum number of iterations
  10. h=0.001 ! Step-size
  11.  
  12. !Initial Guess x0:-
  13. 1 print*,"Enter the inital Guess:-"
  14. read(*,*)x0
  15.  
  16. ! Function and its derivative at x0:-
  17. fx = f(x0)
  18. df_dx = dfdx(x0)
  19.  
  20. !Checking the validity of the inital guess:-
  21. if(fx > 0.0)then
  22. print*,"Initial guess must be such that f(initial guess) should be close to 0."
  23. goto 1
  24. end if
  25.  
  26. ! Newton-Raphson iteration:-
  27. iter = 0
  28. do while (abs(fx) >= tol .and. iter < max_iter)
  29. x = x0 - fx / df_dx ! Compute next approximation of root
  30. iter = iter + 1
  31. x0 = x
  32. fx = f(x0)
  33. df_dx = dfdx(x0)
  34. end do
  35.  
  36. ! Output the results:-
  37. if (iter == max_iter) then
  38. print *,'Newton-Raphson method did not converge within ', max_iter, ' iterations.'
  39. else
  40. print *,'Root found: ',x0
  41. print *,'Number of iterations: ',iter
  42. end if
  43.  
  44. end
Success #stdin #stdout 0.01s 5312KB
stdin
4.0
stdout
 Enter the inital Guess:-
 Root found:    3.61507177    
 Number of iterations:            3