负数组平方根的复数

Complex Number from square root of negative array

我是从 Matlab 到 python 的新转换者,我正在为复杂数组的生成而苦苦挣扎。

在 matlab 中我有以下代码:

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

我正在尝试在 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)

但是,我收到以下错误:

  RuntimeWarning: invalid value encountered in sqrt

我进行了一些谷歌搜索,但我不确定在这种情况下如何模仿 matlab 的行为?有什么建议吗?

一种方法是将 fz 转换为复数 dtype:

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

@PaulPanzer 建议的另一种方式 -

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

这直接来自 numpy docs

输出

[[ 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]]