How to calculate any negative number to the power of some fraction in R?

前端 未结 2 1299
一个人的身影
一个人的身影 2020-12-03 22:57

In the following code:

(-8/27)^(2/3)

I got the result NaN, despite the fact that the correct result should be 4/9

相关标签:
2条回答
  • 2020-12-03 23:08

    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
    
    0 讨论(0)
  • 2020-12-03 23:08

    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.

    0 讨论(0)
提交回复
热议问题