Calculate derivative and integrals in R

Asked

Viewed 1,129 times

4

I have a set of functions that I need to calculate their respective derivatives and integrals. Because there are many I thought it best to create a function that takes an expression as an argument and calculates the derivative and the integral. The problem is I usually use expression to calculate derivatives and function to calculate integrals (otherwise I can’t do), for example:

Derivative:

> y = expression(1/(x+1) * sqrt(x))
> (D.x = D(y, "x"))
1/(x + 1) * (0.5 * x^-0.5) - 1/(x + 1)^2 * sqrt(x)

Integral:

> y = function(x){1/((x+1) * sqrt(x))}
> integrate(y, lower = 0, upper = Inf)
3.141593 with absolute error < 2.7e-05

I don’t want to have to run the parameter twice (one of the kind function for the integral and other type expression for derivative), it would be very laborious. But also do not know any way to convert one type to another.

Just to illustrate, that’s what I want to do:

calcula = function(f, k, a, b)
{
    (D.x = D(f, "x"))
    x = 1
    eval(D.x)
    integrate(f, lower = a, upper = b) #erro aqui
}

calcula(expression(1/(x+1) * sqrt(x), 1, 0, Inf)

1 answer

3


See if this is what you want.
The trick is to use body to give value to the body of the function, as it is on the help page help('body').

calcula <- function(e, k, a, b){
  D.x <- D(e, "x")
  f <- function(x){}
  body(f) <- as.call(c(as.name("{"), e))
  x <- k
  list(
    derivada = eval(D.x),
    integral = integrate(f, lower = a, upper = b) #erro aqui
  )
}

calcula(expression(1/((x+1) * sqrt(x))), 1, 0, Inf)
#$derivada
#[1] -0.5
#
#$integral
#3.141593 with absolute error < 2.7e-05

Browser other questions tagged

You are not signed in. Login or sign up in order to post.