Suppose i have integral
Integral(x^2*sin(x), (x, 0, 1))
I can self solve it manually.
1.The answer in formula
2.or or in numerical form =0.223244275483933
and plot i think will be something like that
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)