Why raising a vector of negative values to a fractional power gives NaN

108 Views Asked by At

If I generate a vector of values, some of which are negative:

d <- rnorm(1000, 4, 10)
z <- sapply(d, function(x) x^1.2)

z will contain a mix of real values and NaNs. Any values that were originally negative in the vector will be NaN.

Why is this? How can I fix it?

2

There are 2 best solutions below

4
ThomasIsCoding On BEST ANSWER

You should use complex numbers, like below

(d + 0i)^1.2
1
Union find On

Thanks to a comment on a post, I learned this:

Users are sometimes surprised by the value returned, for example why (-8)^(1/3) is NaN. For double inputs, R makes use of IEC 60559 arithmetic on all platforms, together with the C system function ‘⁠pow⁠’ for the ^ operator. The relevant standards define the result in many corner cases. In particular, the result in the example above is mandated by the C99 standard. On many Unix-alike systems the command man pow gives details of the values in a large number of corner cases.

You can see more with the ?"^" documentation.

The code can be resolved with:

as.complex(d)^1.2