How to represent polynomials with numeric vectors in R

和自甴很熟 提交于 2019-11-30 07:54:22

问题


In R how would one represent polynomial expressions and do polynomial math with the numeric vector objects? For example:

x1 <- c(2,1)  # 2 + x
x2 <- c(-1,3)  # -1 + 3*x

And want:

x1 * x2 # to return -2 + 5*x + 3*x^2 

Note: I answered a question this morning and then the poster apparently deleted it (making me wonder if it were homework.) So I am re-posting the question from memory.


回答1:


One could multiply the coefficients directly using outer and then aggregate the results

x1 <- c(2,1)  # 2 + x
x2 <- c(-1,3)  # -1 + 3*x
tmp <- outer(x1, x2)
tapply(tmp, row(tmp) + col(tmp) - 1, sum)
# 1  2  3 
#-2  5  3

x1 <- c(2, 1) # 2 + x
x2 <- c(-1, 3, 2) # -1 + 3*x + 2*x^2
tmp <- outer(x1, x2)
tapply(tmp, row(tmp) + col(tmp) - 1, sum) # should give -2 + 5*x + 7*x^2 + 2*x^3
# 1  2  3  4 
#-2  5  7  2

as discussed in the comments the '-1' in the code isn't necessary. When coming up with the solution that helped me because it allowed me to map each location in the output of outer to where it would end up in the final vector. If we did a '-2' instead then it would map to the exponent on x in the resulting polynomial. But we really don't need it so something like the following would work just as well:

tmp <- outer(x1, x2)
tapply(tmp, row(tmp) + col(tmp), sum)



回答2:


Use the polynom package:

 require(polynom)
# Loading required package: polynom
# From the example for as.polynomial
 p <- as.polynomial(c(1,0,3,0))
 p
# 1 + 3*x^2 

 x1 <- c(2,1)
 x2 <- c(-1,3)
 px1 <- as.polynomial(x1)
 px2 <- as.polynomial(x2)

 px1*px2
# -2 + 5*x + 3*x^2 
 prod.p <- .Last.value
 str(prod.p)
# Class 'polynomial'  num [1:3] -2 5 3
 unclass(prod.p)
# [1] -2  5  3



回答3:


Polynomial multiplication is the convolution of the coefficients

convolve(c(2,1),rev(c(-1,3)),type="open")
#[1] -2  5  3


来源:https://stackoverflow.com/questions/16864392/how-to-represent-polynomials-with-numeric-vectors-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!