[英]Build cubic root function in r that returns both negative and positive numbers
I'm trying to build a cubic root function that returns this output:我正在尝试构建一个返回此输出的三次根函数:
cr(27)
output:输出:
3
cr(-27)
output:输出:
-3
I tried the following:我尝试了以下方法:
cr<- function(x){
if(x < 0 & x> 0 & x== 0){
cat("Error, not possible ")
}
else{
cat((x^(1/3)))
cat(" ")
}
}
I'm getting error for -27:我收到 -27 的错误:
Nan
R is giving you one of the cube roots. R 给你一个立方根。 The one it's giving you happens to be complex.它给你的恰好是复杂的。
x <- -27
as.complex(x)^(1 / 3)
#> [1] 1.5+2.598076i
If you want the real root, calculate it like this.如果你想要真正的根,像这样计算。
sign(x) * abs(x)^(1 / 3)
#> [1] -3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.