[R] Coefficients of a factorized polynomial

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Oct 9 09:35:35 CEST 2006


Serguei Kaniovski <kaniovsk at wsr.ac.at> writes:

> Hi all,
> 
> starting from a vector "v[1:n]" I would like to compute the coefficients
> of the polynomial (1+x^v[1])*(1+x^v[2])*...*(1+x^v[n]). The following
> code works but is extremely slow for a large "n" due to, I believe, the
> polynomial being factorized. I wanted to try the package "polynom"
> command "unclass" but I could not figure out how to input a factorized
> polynomial. Can you please help?
> 
> Serguei
> 
> v<-c(1,1,2,3,4,6)
> 
> e<-parse(text=paste("(1+x^", v, sep="", collapse="*", ")"))
> 
> DD<-function(expr, name, order = 0) {
> 	if(order == 0)expr
> 	else DD(D(expr, name), name, order - 1)
> }
> 
> sapply(0:18, function(i) eval(DD(e, "x", i), list(x=0)))/factorial(0:18)

You can do this much more efficiently by working directly with the
polynomial: Represent them as vectors of length sum(v)+1, then

c(1, 0, ..., 0) 

is the polynomial 1, multiply by x^n is right-shift by n, and add is
add.

> v<-c(1,1,2,3,4,6)
> y <- rep(0,18)
> y[1] <-1
> for (i in v) y <- y+c(rep(0,i),y)[1:18]
> y
 [1] 1 2 2 3 4 4 5 6 5 5 6 5 4 4 3 2 2 1



-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list