1

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?

Fatima_Ali
  • 194
  • 9

2 Answers2

1

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)))

majdsalloum
  • 516
  • 1
  • 4
  • 17
  • yes, but I mean by the `sqrt(-1)` is the value of imaginary number `j`. How can I replace it with `j`? – Fatima_Ali Aug 29 '21 at 12:18
  • 1
    @Fatima_Ali that would be `np.sqrt(-1+0j)` – majdsalloum Aug 29 '21 at 12:20
  • 1
    @JohnColeman that would work as well, but if you need the square root of a complex variable then np.sqrt(x + k*1j) would be more dynamic – majdsalloum Aug 29 '21 at 12:25
  • @JohnColeman did you try the code ? it works perfectly fine , as for your first point it's right `0.5 * 2 is redundant` but the problem was with nan and how to get rid with while getting the square root of -1 , i did edit my answer to mark the range to numpy array conversion – majdsalloum Aug 29 '21 at 12:33
1

you need complex class like below:

import cmath

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

output:

array([0.+0.j        , 0.+3.14159265j, 0.+6.28318531j, 0.+9.42477796j])
I'mahdi
  • 23,382
  • 5
  • 22
  • 30