问题描述
我正在尝试在R中而不是从数值上获得三次方程的解.
I'm trying to get solution of cubic equations analytically in R, not numerically.
我在互联网上查询了立方根的公式,并编写了以下代码:链接为: http://www.math.vanderbilt.edu/~schectex/课程/立方/
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
}
但是,该函数在大多数情况下不起作用,我想这是因为公式中具有负数的功效,例如,我注意到R无法获得(-8)^(1/3)的实根是-2.但是我不确定如何修复我的代码,以便通常可以将其用于解决精确的三次解.
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.
谢谢.
推荐答案
尝试一下:
# 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
这篇关于如何在R中解析求解三次方程式(精确解)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!