[Numpy-discussion] help on fast slicing on a grid

Robert Kern robert.kern at gmail.com
Fri Jan 30 15:52:27 EST 2009


On Fri, Jan 30, 2009 at 12:58, frank wang <f.yw at hotmail.com> wrote:
> I have created a test example for the question using for loop and hope
> someone can help me to get fast solution. My data set is about 2000000 data.
>
> However, I have the problem to run the code, the Out[i]=cnstl[j] line gives
> me error says:
>
> In [107]: Out[0]=cnstl[0]
> ---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call last)
> C:\Frank_share\qamslicer.py in <module>()
> ----> 1
>       2
>       3
>       4
>       5
> TypeError: can't convert complex to float; use abs(z)
> In [108]: cnstl.dtype
> Out[108]: dtype('complex128')
>
> I do not know why that my data is complex128 already. Can anyone help to
> figure why?

It's an odd error message, certainly. The root of the problem is that
you are attempting to put a (1,)-shaped array into a scalar. You don't
want to do that.

By the way, you don't want to use the variable name Out in IPython.
It's already used to capture the output.

> Thanks
>
> Frank
>
> from numpy import *
> a = arange(-15,16,2)
> cnstl=a.reshape(16,1)+1j*a
> cnstl=cnstl.reshape(256,1)

Change that line to

  cnstl = cnstl.ravel()

> X = array([1.4 + 1j*2.7, -4.9 + 1j*8.3])
> Out = array(X)
> error =array(X)
> for i in xrange(2):
>     for j in xrange(256):
>         a0 = real(X[i]) < (real(cnstl[j])+1)
>         a1 = real(X[i]) > (real(cnstl[j])-1)
>         a2 = imag(X[i]) > (imag(cnstl[j])-1)
>         a3 = imag(X[i]) < (imag(cnstl[j])+1)
>  if (a0 & a1 & a2 &a3):
>             Out[i] = cnstl[j]
>             error[i] = X[i] - cnstl[j]

After reindenting this correctly, I get the following results:

In [22]: out
Out[22]: array([ 1.+3.j, -5.+9.j])

In [23]: error
Out[23]: array([ 0.4-0.3j,  0.1-0.7j])


Are those correct?

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list