module myutils
   interface 
      function f(x)
      real::x,f
      end function 
   end interface
end module

program simptrap
   implicit none
   real::javab,a,b
   integer::n
   a=0.0; b=1.0;
   n=600;
   call trap(a,b,n,javab)
   write(*,*) "the trap answer for N=",n,"is",javab
   n=10;
   call simpson(a,b,n,javab)
   write(*,*) "the simpson answer for N=",n,"is",javab
end program

subroutine simpson(a,b,n,ans)
   use myutils
   implicit none
   real::a,b,ans,h,xj,xjp
   integer::j,N
   h=(b-a)/real(N-1.0)
   ans=(f(a)+f(b))/3.0
   do j=2,N-2,2
      xj=a+(j-1.0)*h
      xjp=xj+h
      ans=ans+(4.0/3.0*f(xj)+2.0/3.0*f(xjp))
   enddo
   ans=ans*h
end subroutine

subroutine trap(a,b,n,ans)
   use myutils
   implicit none
   real::a,b,ans,h
   integer::N,j
   h=(b-a)/real(N-1.0)
   ans=f(a)*h/2.0+f(b)*h/2.0
   do j=2,N-1
      ans=ans+h*f(a+(j-1)*h)
   enddo
end subroutine


function f(x)
   implicit none
   real::x,f
   f=exp(-x)
end function
