简体   繁体   English

将带负数的向量提升到R中的小数指数

[英]Raising vector with negative numbers to a fractional exponent in R

I have a vector of numbers that contains negative numbers and I would like to raise it to a fractional exponent, but can't quite figure out how to do it. 我有一个包含负数的数字向量,我想把它提升到一个小数指数,但不能弄清楚如何做到这一点。 Here is some example code. 这是一些示例代码。

a = seq(5,-5,1)
b = a^(5/2)

b returns NAN values when a is negative. a为负时, b返回NAN值。 However, 然而,

d = -5^(5/2) 

works. 作品。 I know that this is because of precedence in R, but how to do I what I want, which is to multiply by the absolute value of a , and then assign the negative (while also assessing the possibility that a == 0 )? 我知道这是因为R中的优先级,但我怎么做我想要的,即乘以a的绝对值,然后分配负数(同时还评估a == 0的可能性)?

I know this is more of math and R question than statistics, so if it needs to be moved I will do so. 我知道这更像是数学和R问题而不是统计数据,所以如果需要移动我会这样做。

exponent <- function(a, pow) (abs(a)^pow)*sign(a)
b = rep(NA,length(a))       # create a vector of length equal to length of a
b[a>=0] =  ( a[a>=0])^(5/2) # deal with the non-negative elements of a
b[a< 0] = -(-a[a< 0])^(5/2) # deal with the negative elements of a

Maybe not the most efficient way to do it, but the idea should be usable. 也许不是最有效的方法,但这个想法应该是可用的。

Your contradictory result stems from the fact that the power as a kind of multiplication binds stronger than the negation. 你的矛盾结果源于这样一个事实:作为一种乘法的力量比否定更强大。 Ie, 也就是说,

-5^(5/2) = - ( 5^(5/2) ).

This kind of fractional power should rightly not be defined for negative arguments. 对于否定论证,这种分数权力应该是正确的。 It would be the solution of 这将是解决方案

x^2 = (-5)^5 = - 5^5

which is impossible to solve in real numbers. 这是不可能实际解决的。

Fractional powers of complex numbers is a can of worms that you really should not want to open. 复数的分数幂是一种你真的不应该打开的蠕虫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM