`x^(1/3)`对于负标量`x` x`和vector'x`的行为有所不同
R似乎对计算负数的奇数词根非常满意
-0.2^(1/3) # returns a good number
# [1] -0.5848035
,但是如果将向量提高到1/3,就会发生一些奇怪的事情。
c(-0.2, 1)^(1/3) # returns an NA for the first element
# [1] NaN 1
我对一个答案感兴趣,该答案解释了与向量的不同的不同的 不同于作为数字标量时的负值。
我不是在寻找解决方法函数(x){sign(x)*(abs(x))^(1/3)}
。此答案似乎指向一个很好的方向...“^”操作员如何对向量和标量有不同的看法?
R seems pretty comfortable with computing the odd root of a negative number
-0.2^(1/3) # returns a good number
# [1] -0.5848035
but something weird happens if you raise a vector to the 1/3.
c(-0.2, 1)^(1/3) # returns an NA for the first element
# [1] NaN 1
I'm interested in an answer that explains what is happening differently to the vector than to the negative value when provided as a numeric scalar.
I'm not looking for a workaround e.g. function(x){sign(x)*(abs(x))^(1/3)}
. This answer seems to point in a good direction... how does the "^" operator think differently about vectors and scalars?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎认为
c(-0.2,1)^(1/3)
转换为c(-0.2^(1/3),1^(1/3))< /代码>。这是不正确的。操作员
^
实际上是一个函数,即(a)^(b)
与“^”(a,b)
一样。因此,正确的解释如下:现在,为什么
-0.2^(1/3)
给出nan
?因为^
的操作优先级高于+
, - ,*
和和/
。因此,正如书写的那样,它确实意味着- (0.2^(1/3))
而不是(-0.2)^(1/3)
。教训是,为了避免出现故障代码,将您的代码写入
(a) ^(b)
而不是a ^ b
。其他注释:
我经常比较
^
和:
在向我的学生教授 r 时,因为他们的行为不同。但是它们都表明了用括号保护操作数的重要性。有关操作员优先级的详细信息,请参见
?语法
。You seem to believe that
c(-0.2, 1)^(1/3)
translates toc(-0.2^(1/3), 1^(1/3))
. This is incorrect. Operator^
is actually a function, that is,(a) ^ (b)
is as same as"^"(a, b)
. Therefore, the correct interpretation goes as follows:Now, why doesn't
-0.2^(1/3)
giveNaN
? Because^
has higher operation precedence than+
,-
,*
and/
. So as it is written, it really implies-(0.2^(1/3))
instead of(-0.2)^(1/3)
.The lesson is that, to avoid buggy code, write your code as
(a) ^ (b)
instead of justa ^ b
.Additional Remark:
I often compare
^
and:
when teaching R to my students, because they have different behaviors. But they all show the importance of protecting operands with brackets.See
?Syntax
for details of operator precedence.