[SciPy-User] numpy array root operation

Nathaniel Smith njs at pobox.com
Thu Mar 22 16:26:35 EDT 2012


On Thu, Mar 22, 2012 at 2:43 AM, Odin Den <hate_pod at yahoo.com> wrote:
> Hi,
> 5th root of -32 can be computed correctly as follows:
>>>> -32**(1/5)
>>>> -2.0
>
> However, when I try to perform same operation on numpy arrays I get
> the following:
>>>> array([-32])**(1/5)
>>>> array([ nan])
>
> Is there anyway to compute roots of numpy arrays? I have a huge matrix which
> contains both negative and positive values. What is the easiest way of making
> python compute the "nth" roots of each element of this matrix without knowing
> the value of "n" a priory?

As long as you *know* that what you're computing is an odd root, and
that what you want for negative numbers is the real root, then you
could just work around this:
  roots = np.sign(a) * (a * np.sign(a))**(1./5)

-- Nathaniel



More information about the SciPy-User mailing list