i want combine expressions add them together, or division (code below), , i'm getting error:
non-numeric argument binary operator
how combination?
a=0 fun2 = expression(sin(x)) fun4 = expression(sin(pi/4)) n=1 while(n<3){ fun1 = fun2 fun2 = d(fun1,"x") fun3 = expression(fun2/(prod(1:n)*(x-1)^n)) fun4 = expression(fun4+fun3) n=n+1 }
here recursive implementation build taylor expansion. result of class "call", can evaluate expression. builds expression tree, adding each additional term in taylor expansion recursively.
taylor <- function(f, a, deg, curr=null) { if (is.function(f)) f <- body(f) # use body of function derivatives ## base cases if (missing(curr)) return( as.call(list(`+`, eval(f, list(x=a)), taylor(f, a, deg, 1))) ) if (curr == deg+1) return ( 0 ) ## build each additional term return ( as.call(list(`+`, as.call(list(`/`, as.call(list(`*`, eval(d(f, "x"), list(x=a)), as.call(list(`^`, as.call(list(`-`, quote(x), a)), curr)))), prod(1:curr))), taylor(d(f, "x"), a, deg, curr=curr+1))) ) } you can see expression returns
## function, parameters f <- function(x) sin(x) <- 0 (t3 <- taylor(f, a, 3)) # .primitive("+")(0, .primitive("+")(.primitive("/")(.primitive("*")(1, # .primitive("^")(.primitive("-")(x, 0), 1)), 1), .primitive("+")(.primitive("/")(.primitive("*")(0, # .primitive("^")(.primitive("-")(x, 0), 2)), 2), .primitive("+")(.primitive("/")(.primitive("*")(-1, # .primitive("^")(.primitive("-")(x, 0), 3)), 6), 0)))) and, see if working
## @ xs <- seq(-4, 4, len=100) curve(f, -4, 4, type="p", pch=".", cex=4, main="approximations of sin(x) @ x=1", ylim=c(-2, 2)) cols <- colorramppalette(c("orange", "red"))(7) with(list(x=xs), { (i in 1:7) points(xs, eval(taylor(f, a=1, i)), col=cols[i], lty=2, type="l", lwd=2) }) 
Comments
Post a Comment