How to solve cubic equation analytically (exact solution) in R?

ElaineC picture ElaineC · Mar 24, 2014 · Viewed 7k times · Source

I'm trying to get solution of cubic equations analytically in R, not numerically.

I looked up on the internet and get the formula for cubic roots and wrote the following code: The link is: http://www.math.vanderbilt.edu/~schectex/courses/cubic/

cub <- function(a,b,c,d) {
  p <- -b/3/a
  q <- p^3 + (b*c-3*a*(d))/(6*a^2)
  r <- c/3/a
  x <- (q+(q^2+(r-p^2)^3)^0.5)^(1/3)+(q-(q^2+(r-p^2)^3)^0.5)^(1/3)+p
  x
}

However this function doesn't work in most cases and I guess it's because of the power of negative numbers inside the formula, for example I noticed R cannot get the real root of (-8)^(1/3) which is -2. But Im not sure how I could fix my code so that it can be used to solve for exact cubic solutions in general.

Thanks.

Answer

Josh O&#39;Brien picture Josh O'Brien · Mar 24, 2014

I'd use polyroot(). See here for more details.

polyroot(z = c(8,0,0,1))
# [1]  1+1.732051i -2+0.000000i  1-1.732051i