我一直试图找到一个返回方程的所有复杂解的函数,例如:
16^(1/4) = 2+i0, -2+i0, 0+i2, 0-i2
Run Code Online (Sandbox Code Playgroud)
就目前而言,如果我进入16^(1/4)控制台,它只返回2.我可以为此编写一个函数,但我想知道是否有一种简单的方法在R中执行此操作.
Jos*_*ien 11
你需要polyroot():
polyroot(z = c(-16,0,0,0,1))
# [1] 0+2i -2-0i 0-2i 2+0i
Run Code Online (Sandbox Code Playgroud)
其中z"多项式系数的向量按递增顺序".
我z在上面的例子中传递的向量是这个等式的紧凑表示:
-16x^0 + 0x^1 + 0x^2 + 0x^3 + 1x^4 = 0
x^4 - 16 = 0
x^4 = 16
x = 16^(1/4)
Run Code Online (Sandbox Code Playgroud)
编辑:
如果polyroot你的语法困扰你,你可以编写一个包装函数,为你提供一个更好的(如果不太通用)接口:
nRoot <- function(x, root) {
polyroot(c(-x, rep(0, root-1), 1))
}
nRoot(16, 4)
# [1] 0+2i -2-0i 0-2i 2+0i
nRoot(16, 8)
# [1] 1.000000+1.000000i -1.000000+1.000000i -1.000000-1.000000i
# [4] 1.000000-1.000000i 0.000000+1.414214i -1.414214-0.000000i
# [7] 0.000000-1.414214i 1.414214+0.000000i
Run Code Online (Sandbox Code Playgroud)