ElaineC - 11 months ago 79

R Question

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 Source

Try this:

```
> # calcaulate -8 as a complex number
> z <- as.complex(-8) # or z <- -8 + 0i
>
> # find all three cube roots
> zroot3 <- z^(1/3) * exp(2*c(0:2)*1i*pi/3)
> zroot3
[1] 1+1.732051i -2+0.000000i 1-1.732051i
>
>
> # check that all three cube roots cube to original
> zroot3^3
[1] -8+0i -8+0i -8-0i
```