Home > Mobile >  what is the easiest way to solve the indefinite integral in R
what is the easiest way to solve the indefinite integral in R

Time:04-10

Suppose i have integral

Integral(x^2*sin(x), (x, 0, 1))

I can self solve it manually.

1.The answer in formula

enter image description here

2.or or in numerical form =0.223244275483933

3.or can write it so enter image description here

and plot i think will be something like that enter image description here

So my question. What there is way in R solve indefinite integrals to get answer by formula and in numerical form , like i get when solve it manually, and get the plot? Thank you for your help

CodePudding user response:

Will the integrate function suit your needs for the numerical answer?

my_fun = function(x) {
  x^2*sin(x)
}

integrate(f = my_fun, lower = 0, upper = 1)
#> 0.2232443 with absolute error < 2.5e-15

Created on 2022-04-10 by the reprex package (v0.3.0)

CodePudding user response:

For the symbolic integration, you can use the Rycas package. A basic function to draw both a function and its integral, with appropriate labels, would be something like this:

library(Ryacas)
library(ggplot2)

plot_integral <- function(f, xlim = c(0, 1), ylim = c(0, 2)) {
  
  x <- yac_symbol('x')
  
  integral <- as_r(do.call(integrate, list(f = body(f), var = x)))
  
  fdx <- as.function(list(x = NULL, str2lang(as.character(integral))))
  
  f_lab <- as.character(as.expression(body(f)))
  fdx_lab <- as.character(as.expression(body(fdx)))
  
  ggplot()  
    geom_function(fun = f, mapping = aes(colour = 'function'))  
    geom_function(fun = fdx, mapping = aes(color = 'integral'))  
    lims(x = xlim, y = ylim)  
    geom_label(aes(x = 0.5, y = f(0.5)), label = f_lab, parse = TRUE)  
    geom_label(aes(x = 0.5, y = fdx(0.5)), label = fdx_lab, parse = TRUE)  
    theme_minimal()
}

And all you need to do is pass it a function of x, which it will integrate symbolically, plot, and label:

plot_integral(function(x) cos(x))

plot_integral(function(x) exp(2 * x), ylim = c(0, 10))

plot_integral(function(x) sin(x)   cos(x), ylim = c(-2, 2))

Created on 2022-04-10 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related