我的问题是,我正在尝试计算 $(-1)^{1/3}$,但当我要求 R 计算时,会出现 NaN。
> (-1)^(1/3)
[1] 南
我真的不知道为什么?我正在使用 R 2.15。 我想计算 $(-1)^{1/3}$ 现实生活中$(-1)^{1/3}=-1$应该是-1的立方根。
有什么想法吗?
最佳答案
NaN
的产生是因为 -1
的最大根是复数。您将看到 (-1)^(1/2)
具有相同的行为。这是因为正常计算中不支持复数,正如您所假设的那样,除非您之前强制将基数强制为复数。
尝试
R> (-1+0i)^(1/3)
[1] 0.5+0.866025i
或
R> as.complex(-1)^(1/3)
[1] 0.5+0.866025i
您可以在此处阅读有关立方根的更多信息: http://mathworld.wolfram.com/CubeRoot.html
编辑:
嗯,我上面的建议更多的是解决方法而不是答案。我将尝试更详细地解释它。尽管它很快就会变得非常棘手,因为您需要查看 C 标准库函数。
正如 @whuber 和 @NickCox 在评论中所建议的,答案是 NaN
有一个很好的理由。查看 ^
运算符的源代码,您可以看到这种情况将使用标准库中的 C 函数 double pow (double base, double exponent);
进行计算math.h
。此函数具有相同的行为。
作为示例,您可以查看此实现:http://www.netlib.org/fdlibm/e_pow.c这里你看到有一些特殊情况列出如下:
/*
* Special cases:
* 1. (anything) ** 0 is 1
* 2. (anything) ** 1 is itself
* 3. (anything) ** NAN is NAN
* 4. NAN ** (anything except 0) is NAN
* 5. +-(|x| > 1) ** +INF is +INF
* 6. +-(|x| > 1) ** -INF is +0
* 7. +-(|x| < 1) ** +INF is +0
* 8. +-(|x| < 1) ** -INF is +INF
* 9. +-1 ** +-INF is NAN
* 10. +0 ** (+anything except 0, NAN) is +0
* 11. -0 ** (+anything except 0, NAN, odd integer) is +0
* 12. +0 ** (-anything except 0, NAN) is +INF
* 13. -0 ** (-anything except 0, NAN, odd integer) is +INF
* 14. -0 ** (odd integer) = -( +0 ** (odd integer) )
* 15. +INF ** (+anything except 0,NAN) is +INF
* 16. +INF ** (-anything except 0,NAN) is +0
* 17. -INF ** (anything) = -0 ** (-anything)
* 18. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer)
* 19. (-anything except 0 and inf) ** (non-integer) is NAN
*/
其中 19 对应于您的情况。在这种情况下,它放弃并返回 nan
。
/* (x<0)**(non-int) is NaN */
if((n|yisint)==0) return (x-x)/(x-x);
好的。那么当我们将基数改为复杂时会发生什么?
然后我们将使用 complex.h
库中的函数 double complex cpow (double complex x, complex double y)
。该函数可以处理复数,因此不会以同样的方式快捷方式。相反,将结果计算为
double complex cpow (double complex base, double complex power)
{
return cexp (power * clog (base));
}
这与您在 @whuber 的评论中看到的相同。除了这个函数可以处理复数。
我不确定这个解释是否更好,尽管它涉及细节,但我希望我已经以某种方式回答了你的问题。
关于r - 为什么这给我一个 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169863/