1

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?

dan burke
  • 53
  • 7

2 Answers2

5

One way is casting fz to complex dtype:

ifz = np.sqrt(fz.astype(np.complex))
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
1

Another way apart from what @PaulPanzer suggested -

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

from numpy.lib.scimath import sqrt as csqrt
ifz = csqrt(fz)

print ifz

This comes straight from the numpy docs

Output

[[ 0.+179.60512242j  0.+178.89941308j  0.+178.19652073j ...,
   0.+178.19652073j  0.+178.89941308j  0.+179.60512242j]
 [ 0.+178.89941308j  0.+178.19090886j  0.+177.48521065j ...,
   0.+177.48521065j  0.+178.19090886j  0.+178.89941308j]
 [ 0.+178.19652073j  0.+177.48521065j  0.+176.7766953j  ...,
   0.+176.7766953j   0.+177.48521065j  0.+178.19652073j]
 ..., 
 [ 0.+178.19652073j  0.+177.48521065j  0.+176.7766953j  ...,
   0.+176.7766953j   0.+177.48521065j  0.+178.19652073j]
 [ 0.+178.89941308j  0.+178.19090886j  0.+177.48521065j ...,
   0.+177.48521065j  0.+178.19090886j  0.+178.89941308j]
 [ 0.+179.60512242j  0.+178.89941308j  0.+178.19652073j ...,
   0.+178.19652073j  0.+178.89941308j  0.+179.60512242j]]
Vivek Kalyanarangan
  • 8,951
  • 1
  • 23
  • 42