fork download
  1. program r_f
  2. implicit none
  3. real :: p,q,eps,x,x1,fp,fq,fx
  4. integer :: choice,i,max_i
  5.  
  6. print*,"Enter a, b, epscilon, max_iteration"
  7. read*, p, q, eps, max_i
  8. print*,"Choose : 1 =Bisection, 2 = Newton, 3=Iteration, 4= Regula Falsi"
  9. read*, choice
  10. select case(choice)
  11. case(1)
  12. do i=1,max_i
  13. x = (p+q)/2.0
  14. fp = f(p); fq=f(q); fx=f(x)
  15. if(abs(fx)<eps) exit
  16. if(fp*fx<0) then
  17. q=x
  18. else
  19. p=x
  20. end if
  21. end do
  22. print*,"Root(Using Bisection) = ", x
  23.  
  24. case(2)
  25. x = (p+q)/2.0
  26. do i=1,max_i
  27. x1 = x - f(x)/df(x)
  28. if(abs(x1-x)<eps) exit
  29. x = x1
  30. end do
  31. print*,"Root(Using Newton Raphson) = ", x
  32.  
  33. case(3)
  34. x = (p+q)/2.0
  35. do i=1,max_i
  36. x1 = g(x)
  37. if(abs(x1-x)<eps) exit
  38. x = x1
  39. end do
  40. print*,"Root(Using Iteration) = ", x
  41.  
  42. case(4)
  43. fp=f(p);fq=f(q)
  44. do i=1,max_i
  45. x = (p*fq-q*fp)/(fq-fp)
  46. fx=f(x)
  47. if(abs(x1-x)<eps) exit
  48. if(fp*fx<0) then
  49. q = x ; fq=fx
  50. else
  51. p = x
  52. fp=fx
  53. end if
  54. end do
  55. print*,"Root(Using Regula Falsi) = ", x
  56. end select
  57. contains
  58. real function f(x)
  59. real, intent(in) :: x
  60. f = x*x - 4.0
  61. end function
  62.  
  63. real function df(x)
  64. real, intent(in) :: x
  65. df = x*2.0
  66. end function
  67.  
  68. real function g(x)
  69. real, intent(in) :: x
  70. g = sqrt(4.0)
  71. end function
  72. end program r_f
Success #stdin #stdout 0.01s 5288KB
stdin
1 3 0.1 20
1
stdout
 Enter a, b, epscilon, max_iteration
 Choose : 1 =Bisection, 2 = Newton, 3=Iteration, 4= Regula Falsi
 Root(Using Bisection) =    2.00000000