【问题标题】:is cmath.square working for numpy arrays?cmath.square 是否适用于 numpy 数组?
【发布时间】:2022-10-24 07:05:29
【问题描述】:

我想计算一个 numpy 负数数组的平方根。

我尝试使用np.sqrt(),但它给出了错误,因为域。

然后,我发现对于复数,您可以使用cmath.sqrt(x),但它也会给我一个错误。

这是我的代码

import numpy as np
import cmath
from cmath import sqrt

x = np.arange(-10, 10, 0.01)
E = 1

p1 = cmath.sqrt(E - x**2)

并得到了这个错误

Traceback (most recent call last):
  File "C:\Users\os.py", line 49, in <module>
    p1 = cmath.sqrt(E - x**2)
TypeError: only length-1 arrays can be converted to Python scalars

后来我尝试使用 for 循环,这也是不可能的。 这是代码:

import numpy as np
import cmath
from cmath import sqrt

x = np.arange(-10, 10, 0.01)
E = 1

for i in range(0, len(x)):
    p1 = cmath.sqrt(E - x(i)**2)

和消息错误

Traceback (most recent call last):
  File "C:\Users\os.py", line 48, in <module>
    p1 = cmath.sqrt(E - x(i)**2)
TypeError: 'numpy.ndarray' object is not callable

我不知道我做错了什么,有人可以帮助我吗?,拜托。 我需要计算一个 numpy 负数数组的平方根,有人知道该怎么做吗?

【问题讨论】:

  • 我使用emath 添加并回答,但还想提一下您在循环版本中遇到的问题只是语法错误。 x(i) 应该是 x[i]。似乎您正在尝试对数组进行索引,但语法却像函数一样调用它。

标签: python arrays numpy sqrt python-cmath


【解决方案1】:

您可以使用numpy.emath.sqrt(),它将处理负数并返回复数平方根:

import numpy as np

x = np.array([-4, -16, -25, 100, 64])

np.emath.sqrt(x)
# array([ 0.+2.j,  0.+4.j,  0.+5.j, 10.+0.j,  8.+0.j])

【讨论】:

    【解决方案2】:

    是的,您可以迭代以对x 的各个元素执行cmath

    In [254]: np.array([cmath.sqrt(E-i**2) for i in x])
    Out[254]: 
    array([0.+9.94987437j, 0.+9.93982394j, 0.+9.92977341j, ...,
           0.+9.91972278j, 0.+9.92977341j, 0.+9.93982394j])
    

    但是np.sqrt 如果你给它一个复杂的 dtype 数组就可以工作:

    In [255]: np.sqrt(E-x.astype(complex)**2)
    Out[255]: 
    array([0.+9.94987437j, 0.+9.93982394j, 0.+9.92977341j, ...,
           0.+9.91972278j, 0.+9.92977341j, 0.+9.93982394j])
    

    一些比较时间

    In [259]: timeit np.emath.sqrt(E-x**2)
    166 µs ± 336 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
    
    In [260]: timeit np.sqrt(E-x.astype(complex)**2)
    129 µs ± 82.1 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
    
    In [261]: timeit np.array([cmath.sqrt(E-i**2) for i in x])
    2.54 ms ± 4.36 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2021-12-18
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 2014-12-02
      • 2014-04-15
      • 1970-01-01
      相关资源
      最近更新 更多