Search code examples
pythoncomplex-numberspython-cmath

The values of a vector in python are shown as nan value


I have a vector y with size, for example, (1,64). I create a vector in python as follows:

vec = np.pi * np.sqrt(-1) * range(len(y))

I get the output values of the vector vec are all nan or the majority of them are nan.

What i'm trying to accomplish with range(len(y)) in the above code, is to create a vector including 0, 2, 3, ... with the length of y.

How can I solve that issue, please?


Solution

  • You're getting nan because you're using the square root of -1, as for range(len(y)) it creates a range object with items from 0 to len(y) - 1, however you can't use mathematical operations on it as is, you need to pass it to numpy.array or have a numpy object in the expression , (this is satisfied by np.sqrt function), another way would be np.array(range(len(y)))

    a working example:

    vec = 2*np.pi*np.sqrt(1)*0.5*range(len(y))

    if you'd like to use imaginary units you need to express the number as an complex number use the expression i+jk

    so your code would be ( 2 *0.5 removed because it's redundant)

    vec = np.pi*np.sqrt(-1 + 0j)*np.array(range(len(y)))