0

Does anyone have any idea why the following produced a NaN? I am running this on R 4.0.2 on OSX.

> (1.55e-04/-7.35e-05)^(10/(22.77-12.66))
[1] NaN

If I break it down, I also get a NaN

> a <- (1.55e-04/-7.35e-05)
> b <- (10/(22.77-12.66))
> a^b
[1] NaN

But, if I just put in the numbers, I get the correct answer...

> a
[1] -2.108844
> b
[1] 0.9891197
> -2.108844 ^ 0.9891197
[1] -2.091793
5
  • Does this answer your question? R Exponent Produces NaN Commented Oct 26, 2020 at 15:01
  • sign(a)*abs(a)^b works
    – jebyrnes
    Commented Oct 26, 2020 at 15:03
  • It might not produce an error, but you're not making the calculation you want with that. You're doing abs(a)^b, than making that result negative. In order to do the calculation you want, you need to work with complex numbers. Commented Oct 26, 2020 at 15:06
  • For the data I am working with, it is the correct calculation.
    – jebyrnes
    Commented Oct 26, 2020 at 15:18
  • basically the same issue as stackoverflow.com/questions/63005466/… ... you probably want -(2.108844 ^ 0.9891197)
    – Ben Bolker
    Commented Oct 26, 2020 at 15:50

2 Answers 2

3

Do you get the correct answer though? The following works:

-2.108844 ^ 0.9891197
#> [1] -2.091793

And gives the same result as the following:

-(2.108844 ^ 0.9891197)
#> [1] -2.091793

But look what happens if I move the negative sign inside the brackets:

(-2.108844) ^ 0.9891197
#> [1] NaN

Note that R quite appropriately gives NaN because I am raising a negative number to a fractional power.

So the answer to your question is that due to operator precedence, the R parser is interpreting

-2.108844 ^ 0.9891197

as

-(2.108844 ^ 0.9891197)

Which is giving you the wrong answer when you type the numbers directly.

1

You are taking the root of a negative number, so your result is complex, you can't treat it as normal numeric, you need to:

a <- (1.55e-04/-7.35e-05)
b <- (10/(22.77-12.66))
as.complex(a)^as.complex(b)

Output:

-0.1487035-0.6348101i

Possible duplicate of R Exponent Produces NaN

Not the answer you're looking for? Browse other questions tagged or ask your own question.