gpt4 book ai didi

r - 函数内的操作顺序与函数外的操作顺序不同吗?

转载 作者:行者123 更新时间:2023-12-04 00:00:08 27 4
gpt4 key购买 nike

为什么函数中的数学顺序 [PEMDAS] 在 R 中不起作用?
这些工作正常:

-27^(1/3) == -3 # TRUE
-27^0.3333333333333333 == -3 # TRUE
但是这些会导致错误吗?
foo <- function(x, y){return(x^(1/y))}
foo(x = -27, y = 3) # NaN

bar <- function(x, y){
a = 1 / y
b = x^a
return(b)
}

bar(x = -27, y = 3) # NaN
预先感谢您的解释。

最佳答案

由于“一元减号”( - ) 运算符的优先级低得惊人,再加上 R 将负数提高到分数幂的惯例。 -27^(1/3)读作“计算 27^(1/3) (==3),然后反转符号”。如果我们改为计算 (-27)^(1/3) , 我们得到 NaN ,因为负数不能可靠地提高到分数幂。评估是在函数内部还是外部是一个红鲱鱼;问题是 (-27) 是否首先被评估为表达式(如果您将其分配给函数参数或变量,或将其放在括号中)。
一元减号的优先级在 this mailing list thread from 2009 上讨论和 R FAQ 7.33 ,更一般地在此 math.stackexchange question .有一个(相当技术性的)解释为什么分数幂的负值是 NaN?"^" :

Users are sometimes surprised by the value returned, for examplewhy ‘(-8)^(1/3)’ is ‘NaN’. For double inputs, R makes use of IEC60559 arithmetic on all platforms, together with the C systemfunction ‘pow’ for the ‘^’ operator. The relevant standardsdefine the result in many corner cases. In particular, the resultin the example above is mandated by the C99 standard. On manyUnix-alike systems the command ‘man pow’ gives details of thevalues in a large number of corner cases.

关于r - 函数内的操作顺序与函数外的操作顺序不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com