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 03(x2+4x+1)dx\displaystyle \int_{0}^{3} \left( x^2 + 4x + 1 \right) dx and 0exdx\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,

03(x2+4x+1)dx=[13x3+2x2+x]x=03=9+18+3=30 \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

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

can be confirmed.

See Also