c   6.$BFsJ,K!(B($BG\@:EY7W;;(B)
c     $B?9@n(B $BLwBg(B , 22980138
c
      program ex6
c
      implicit none
      real(8) :: a,b,c,d,x1,x2,epsilon

      a= 1.0d0
      b=-4.0d0
      c=-2.0d0
      d= 8.0d0
      epsilon = 1.0d-3

      write(6,*)'$B6h4V(B[-5.0,-2.0]'
        x1=-5.0d0
        x2=-2.0d0
        call device2(a,b,c,d,x1,x2,epsilon)

      write(6,*)'$B6h4V(B[-2.0, 0.0]'
        x1=-2.0d0
        x2= 0.0d0
        call device2(a,b,c,d,x1,x2,epsilon)
      write(6,*)'$B6h4V(B[ 0.0, 2.0]'
        x1= 0.0d0
        x2= 2.0d0
        call device2(a,b,c,d,x1,x2,epsilon)

      write(6,*)'$B6h4V(B[ 2.0, 5.0]'
        x1= 2.0d0
        x2= 5.0d0
        call device2(a,b,c,d,x1,x2,epsilon)

      stop
      end

c-----$BFsJ,K!$G(B3$B<!J}Dx<0(B f(x)=ax**3+bx**2+cx+d $B$N(B
c-----$B2r$HH?I|2s?t$r5a$a$k%5%V%k!<%A%s(B
      subroutine device2(a,b,c,d,x1,x2,epsilon)
       implicit none
       integer :: n
       real(8) :: f,fx1,fx2,fx3,a,b,c,d,x1,x2,x3,epsilon
      
       n=0
       x3=(x1+x2)*0.5d0
       fx1=f(a,b,c,d,x1)
       fx2=f(a,b,c,d,x2)    
       fx3=f(a,b,c,d,x3)  

        if (fx1*fx2 >= 0.0d0) go to 10
        do while (abs(x1-x2) >= epsilon)
          n=n+1
          if (fx1*fx3 <= 0.0d0) then
            x2=x3
            fx2=fx3
          else if (fx1*fx3 > 0.0d0) then
            x1=x3
            fx1=fx3
          end if    
          x3=(x1+x2)*0.5d0
          fx3=f(a,b,c,d,x3)
        enddo

      write(6,200)
      write(6,100) n,x3    
      go to 20
   10 write(6,*) '$B$3$N6h4V$K2r$O$"$j$^$;$s(B'
   20 write(6,*)''  
      return
  100 format(4x,i5,d26.18)
  200 format(1x,'$BH?I|2s?t(B',2x,'$B2r(B') 
      end

c-----$B4X?t(B f(x)=ax**3+bx**2+cx+d
      function f(a,b,c,d,x)
      implicit none
      real(8) :: f,x,a,b,c,d
      
      f=a*x**3+b*x**2+c*x+d

      return
      end
