Home > Back-end >  Expanding polynomial
Expanding polynomial

Time:05-30

I would like to write a function that expands a polynomial in factorized form. The function should accept characters as input, and return the expanded polynomial in standard form (with ordered exponents from highest to lowest).

The output should look like this:

> function("(3x - 2)^2 (2x^3 -1)")
[1] "18x^{5} - 24x^{4}   8x^{3} - 9x^{2}   12x - 4

Thanks!

CodePudding user response:

Insert a * between factors and also one between digits and x and then use polynom to evaluate it.

We could shorten this slightly if we can assume that factors are separated with * and if number followed by x has a * separating them. In that case we could omit the two gsub calls.)

library(polynom)

run <- function(s) {
  s |>
    gsub(pattern = "[{}]", replacement = "") |>
    gsub(pattern = "([)0-9]) *([(])", replacement = "\\1 * \\2") |>
    gsub(pattern = "(\\d)x", replacement = "\\1*x") |>
    str2lang() |>
    eval(list(x=polynomial())) |>
    as.character(decreasing = TRUE) |>
    gsub(pattern = "\\^(\\d )", replacement = "^{\\1}")
}

p <- "(3x - 2)^2 (2x^3 -1)"
run(p)
## [1] "18*x^{5} - 24*x^{4}   8*x^{3} - 9*x^{2}   12*x - 4"

identical(run(run(p)), run(p))
## [1] TRUE

It would be easier not to use strings in the first place and use the polynom package's polynomial class and conventions instead. Then it is just:

x <- polynomial()
(3*x - 2)^2 * (2*x^3 -1)
## -4   12*x - 9*x^2   8*x^3 - 24*x^4   18*x^5 
  • Related