logo

Calculating Definite Integrals in R 📂R

Calculating Definite Integrals in R

Overview

In R, you can use the integrate() function to calculate definite integrals. For example,

Code

To calculate $\displaystyle \int_{0}^{3} \left( x^2 + 4x + 1 \right) dx$ and $\displaystyle \int_{0}^{\infty} e^{-x} dx$, you can use the following. Notably, by including inf in the integration interval, it is possible to perform improper integrals as well.

f<-function(x) {x^2 + 4*x + 1}
g<-function(x) {exp(-x)}
 
integrate(f,0,3)
integrate(g,0,Inf)

20190322_140807.png

Upon actual calculation,

$$ \int_{0}^{3} \left( x^2 + 4x + 1 \right) dx = \left[ {{1} \over {3}} x^{3} + 2 x^2 + x \right]_{x=0}^{3} = 9 + 18 + 3 = 30 $$

and

$$ \int_{0}^{\infty} e^{-x} dx = \left[ - e^{-x} \right]_{x = 0}^{\infty} = 0 - (-1) = 1 $$

can be confirmed.

See Also