Andrew
Andrew

Reputation: 1148

How to derivate using Ryacas

I am totally nil in using the Ryacas package. I would like to get successive derivatives of polynomials, so I tried the following lines:

library(Ryacas)
x <- Sym("x")
P <- 1
for (k in 1:10) {
  P <- (1+k*x)*P + x*(1-x)*deriv(P, x)
  P
}

I expected to obtain the successive polynomials :

P = (1 + x)(1) = 1 + x
P = (1 + 2x)(1 +x) + x(1 - x)(1) = 1 + 4x + x^2
P = (1 + 3x)(1 + 4x + x^2) + x(1 - x)(4 + 2x) = 1 + 11x + 11x^2 + x^3

and so on.

No error is indicated, but no output is displayed. So the writing of my lines is obviously wrong. Could you help me, please ?

Upvotes: 1

Views: 235

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84649

Use P <- Sym(1) at the beginning. Also use Simplify in your loop otherwise the calculations are too time-consuming. You also have to use print in the loop.

library(Ryacas)
x <- Sym("x")
P <- Sym(1)
for (k in 1:10) {
  P <- Simplify((1+k*x)*P + x*(1-x)*deriv(P, x))
  print(P)
}

Result:

expression(3 * x^2 - x^3 + 9 * x + 1)
expression(x^4 - 4 * x^3 + 18 * x^2 + 20 * x + 1)
expression(5 * x^4 - x^5 + 2 * x^3 + 94 * x^2 + 43 * x + 1)
expression(x^6 - 6 * x^5 + 27 * x^4 + 196 * x^3 + 411 * x^2 + 
    90 * x + 1)
expression(7 * x^6 - x^7 - 9 * x^5 + 527 * x^4 + 2017 * x^3 + 
    1593 * x^2 + 185 * x + 1)
expression(x^8 - 8 * x^7 + 40 * x^6 + 1000 * x^5 + 8686 * x^4 + 
    14440 * x^3 + 5704 * x^2 + 376 * x + 1)
expression(9 * x^8 - x^9 - 24 * x^7 + 2280 * x^6 + 32058 * x^5 + 
    101190 * x^4 + 86280 * x^3 + 19368 * x^2 + 759 * x + 1)
expression(x^10 - 10 * x^9 + 57 * x^8 + 4368 * x^7 + 112134 * 
    x^6 + 597108 * x^5 + 937350 * x^4 + 461328 * x^3 + 63417 * 
    x^2 + 1526 * x + 1)
expression(11 * x^10 - x^11 - 43 * x^9 + 9249 * x^8 + 371346 * 
    x^7 + 3173370 * x^6 + 8269398 * x^5 + 7454718 * x^4 + 2289231 * 
    x^3 + 202459 * x^2 + 3061 * x + 1)
expression(x^12 - 12 * x^11 + 78 * x^10 + 18068 * x^9 + 1197279 * 
    x^8 + 15664248 * x^7 + 63560580 * x^6 + 94344696 * x^5 + 
    53298207 * x^4 + 10776596 * x^3 + 634926 * x^2 + 6132 * x + 
    1)

Upvotes: 1

Related Questions