Códigos para cada uma das regras

REGRA RETANGULAR

\[ \hat{I_{R}}=h\sum_{i=1}^{n}f\left ( a+\frac{(2i-1)}{2}h \right ) \]

#Função para regra retangular
intR = function(n,a,b,f,...) {
  h = (b-a)/n
  s = 0
  for (i in 1:n) {
    s = s + f(a + ((2*i - 1)*h)/2,...)
  }
  Ir = h * s
  return(Ir)
}

REGRA TRAPEZOIDAL

\[ \hat{I_{T}}=h\left ( \frac{f(a)}{2}+\sum_{i=1}^{n-1}f(a+ih)+\frac{f(b)}{2} \right ) \]

#Função para regra trapezoidal
intT = function(n,a,b,f,...) {
    h = (b-a)/n
    s = 0
    for (i in 1:(n-1)) {
      s = s + f(a + i*h,...)
    }
    It = h * (f(a,...)/2 + s + f(b,...)/2)
    return(It)
}

REGRA DE SIMPSON

\[ \hat{I_{S}}=\frac{h}{3}\left [ f(a)+4\sum_{i=1}^{n/2}f(a+(2i-1)h)+2\sum_{i=1}^{\frac{n}{2}-1}f(a+2ih)+f(b) \right ] \]

#Função para regra de Simpson
intS = function(n,a,b,f,...) {
  if ((n %% 2) != 0) {
    print("O valor de n não é par, esse método não pode ser implementado.")
  } else {
      h = (b-a)/n
      s1 = 0
      s2 = 0
      for (i in 1:(n/2)) {
        s1 = s1 + f(a + ((2*i)-1)*h,...)
      }
      for (i in 1:((n/2)-1)) {
        s2 = s2 + f(a + 2*i*h,...)
      }
      Is = (h/3) * (f(a,...) + 4*s1 + 2*s2 + f(b,...))
      return(Is)
    }
}

Obs.: function(n,a,b,f,…): o (…) serve para quando a função f tiver mais de um parâmetro, a ser definido depois.

Questões da aula

QUESTÃO 1a

\[ \int_{1}^{3} e^{-x}dx \]

intR(10,1,3,dexp)
## [1] 0.3175628
intT(10,1,3,dexp)
## [1] 0.319152
intS(10,1,3,dexp)
## [1] 0.3180952
#Valor calculado (referência)
I = (1- exp(-3)) - (1- exp(-1))
I
## [1] 0.3180924

QUESTÃO 1b

\[ \int_{0}^{1} e^{x}dx \]

#Como não temos densidade no R para esta função, teremos que implementar com uma nova function
func = function(x) {
  f = exp(x)
  return(f)
}

intR(50,0,1,func)
## [1] 1.718253
intT(50,0,1,func)
## [1] 1.718339
intS(50,0,1,func)
## [1] 1.718282

Questão 1c

\[ \int_{18}^{30}\frac{1}{\sqrt{2\pi*9}}exp\left\{ -\frac{1}{2*9}*\left( x-20 \right)^{2} \right\} \]

intR(100,18,30,dnorm,mean = 20, sd = sqrt(9))
## [1] 0.7470929
intT(100,18,30,dnorm,mean = 20, sd = sqrt(9))
## [1] 0.7470493
intS(100,18,30,dnorm,mean = 20, sd = sqrt(9))
## [1] 0.7470784