Search code examples
matlabnumpysqrt

Complex Number from square root of negative array


I am a new convert from Matlab to python and I am struggling with the generation of a complex array.

In matlab I have the following code:

  xyAxis = linspace(-127,127,255);
  [x,y] = meshgrid(xyAxis, xyAxis);
  fz = -(x.^2 + y.^2);
  ifz = sqrt(fz);

Which I am trying to replicate in python 3:

  import numpy as np
  xyAxis = np.intp( np.linspace(-127, 127, 255) )
  x, y = np.meshgrid(xyAxis,xyAxis)
  fz =  - (x**2 + y**2)
  ifz = np.sqrt(fz)

However, I get the following error:

  RuntimeWarning: invalid value encountered in sqrt

I have done a bit of googling and I am not sure how to mimic the behavior of matlab in this case? Any suggestions?


Solution

  • One way is casting fz to complex dtype:

    ifz = np.sqrt(fz.astype(np.complex))