Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taylor approximation in R

Tags:

r

Is there a function/package in R which takes a function f and a parameter k, and then returns a Taylor approximation of f of degree k?

like image 546
utdiscant Avatar asked Feb 08 '13 02:02

utdiscant


2 Answers

Compare the above symbolic solution with a numerical Taylor approximation:

library(pracma)

p <- taylor(f = exp, x0 = 0, n = 4)             # Numerical coefficients 
# 0.1666667 0.5000000 1.0000000 1.0000000       # x^3/6 + x^2/2 + x + 1

polyval(p, 1:5)                                 # Evaluate the polynomial
# 2.66667  6.33333 13.00000 23.66667 39.33334   # exp(x) at x = 1:5
like image 23
Hans W. Avatar answered Sep 19 '22 18:09

Hans W.


You can use Ryacas to work with the yacas computer algebra system (which you will need to install as well)

Using an example from the vignette

 library(Ryacas)
 # run   yacasInstall() if prompted to install yacas
 #
 yacas("texp := Taylor(x,0,3) Exp(x)")
 ## expression(x + x^2/2 + x^3/6 + 1)
 # or

Now, if you want to turn that into a function that you can give values of x

myTaylor <- function(f, k, var,...){
  .call <- sprintf('texp := Taylor( %s, 0, %s) %s', var,k,f)
  result <- yacas(.call)
  foo <- function(..., print = FALSE){
    if(print){print(result)}
    Eval(result, list(...))}
  return(foo)
}
# create the function
foo <- myTaylor('Exp(x)', 3, 'x')
foo(x=1:5)
## [1]  2.666667  6.333333 13.000000 23.666667 39.333333
foo(x=1:5, print = TRUE)
## expression(x + x^2/2 + x^3/6 + 1)
## [1]  2.666667  6.333333 13.000000 23.666667 39.333333
like image 179
mnel Avatar answered Sep 20 '22 18:09

mnel