rpolynomial-mathpolynomialspolynomial-approximations

Custom changes to polynomial function (polynom) for a variable in R


This question is more for my own curiosity. I was looking through the Polynom documenation pdf for R, and noticed several basic polynomial operations such as:

p <- poly.calc(1:5)
## -120 + 274*x - 225*x^2 + 85*x^3 - 15*x^4 + x^5

However, how would I represent 'x' if I had to solve an equation such as:

(x+1)3x^3 + (x+1)4x^2 + (x+1) 2x + 3 = 17

and as a bonus, what if I wanted to specify x is greater than 0, and would change the equation to (x+1)3x^3 + (x+1)4x^2 + (x+1) 2x + 3 ≈ 17 where x > 0? (if it is even possible)


Solution

  • I think you are asking something like the following:

    With the library polynom:

    library(polynom)
    #(x+1)3x^3 + (x+1)4x^2 + (x+1) 2x + 3 - 17 = (x+1)(3x^3 + 4x^2 + 2x) - 14
    p1 <- polynomial(coef = c(1, 1))
    p2 <- polynomial(coef = c(0, 2, 4, 3))
    p <- p1 * p2 - 14
    roots <- solve(p)
    real.roots <- Re(roots[Im(roots)==0])
    # [1] -2.0554784  0.9069195
    real.positive.roots <- real.roots[real.roots > 0]
    # [1] 0.9069195
    plot(p)
    abline(h=0)
    abline(v=real.roots, lty=2)
    points(real.roots, rep(0, length(real.roots)))
    

    enter image description here

    With the function uniroot:

    f <- function (x) (x+1)*3*x^3 + (x+1)*4*x^2 + (x+1)*2*x + 3 - 17
    root1 <- uniroot(f, c(-2, 1), tol = 0.0001)$root
    # [1] 0.9069388
    root2 <- uniroot(f, c(-3, -2), tol = 0.0001)$root
    # [1] -2.055487
    
    x <- seq(-2.5,1.5,0.001)
    plot(x, f(x), type='l')
    abline(h=0)
    abline(v=root1, lty=2)
    abline(v=root2, lty=2)
    points(root1, 0, col='red', pch=19)
    points(root2, 0, col='red', pch=19)
    

    enter image description here