Reputation: 31965
In the following code:
(-8/27)^(2/3)
I got the result NaN
, despite the fact that the correct result should be 4/9
or .444444...
.
So why does it return NaN? And how can I have it return the correct value?
Upvotes: 9
Views: 6908
Reputation: 263342
Here's the operation in the complex domain, which R does support:
(-8/27+0i)^(2/3)
[1] -0.2222222+0.3849002i
Test:
> ((-8/27+0i)^(2/3) )^(3/2)
[1] -0.2962963+0i
> -8/27 # check
[1] -0.2962963
Furthermore the complex conjugate is also a root:
(-0.2222222-0.3849002i)^(3/2)
[1] -0.2962963-0i
To the question what is the third root of -8/27:
polyroot( c(8/27,0,0,1) )
[1] 0.3333333+0.5773503i -0.6666667-0.0000000i 0.3333333-0.5773503i
The middle value is the real root. Since you are saying -8/27 = x^3 you are really asking for the solution to the cubic equation:
0 = 8/27 + 0*x + 0*x^2 + x^2
The polyroot
function needs those 4 coefficient values and will return the complex and real roots.
Upvotes: 7
Reputation: 176648
As documented in help("^")
:
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.
So you need to do the operations separately:
R> ((-8/27)^2)^(1/3)
[1] 0.4444444
Upvotes: 8