2015-07-21 66 views
3

表達式組合我想通過添加它們表現結合在一起,或師(下面的代碼),而且我得到一個錯誤:如何R中

non-numeric argument to binary operator

如何獲得組合?

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 
} 
+1

你可以試試'FUN3 < - 表達(EVAL (fun2)/(prod(1:N)*(x-1)^ N))'和'fun4 < - 表達式(eval(fun4)+ eval(fun3))'。 – RHertel

+2

無論如何,你想用這些表達式做什麼?我不確定我在這裏的目標是否理解。 – MrFlick

+0

試圖獲得一個函數的泰勒公式,然後通過設置x值來繪製結果 – YoarkYANG

回答

2

這是一個遞歸實現來構建泰勒擴展。結果是類「呼叫」,但你可以評估它,就像你會表達。它基本上只是建立一個表達式樹,遞歸地在泰勒展開式中添加每個附加術語。

taylor <- function(f, a, deg, curr=NULL) { 
    if (is.function(f)) f <- body(f) # use the body of the function for 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 function, parameters 
f <- function(x) sin(x) 
a <- 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)))) 

而且,看看它是否工作

## Look at it 
xs <- seq(-4, 4, len=100) 
curve(f, -4, 4, type="p", pch=".", cex=4, main="Approximations of sin(x) at x=1", 
     ylim=c(-2, 2)) 

cols <- colorRampPalette(c("orange", "red"))(7) 
with(list(x=xs), { 
    for (i in 1:7) 
     points(xs, eval(taylor(f, a=1, i)), col=cols[i], lty=2, type="l", lwd=2) 
}) 

enter image description here