【问题标题】:keep getting 'only length-1 arrays can be converted to python scalars'不断得到“只有长度为 1 的数组可以转换为 python 标量”
【发布时间】:2019-10-30 16:00:56
【问题描述】:

我不断收到错误only length-1 arrays can be converted to Python scalars。由于变量 'uc' 是一个包含 214 个元素的数组,我收到错误消息。

错误状态:

  File "/home/lokesh/PycharmProjects/Cross_Range_Imaging/Cross_Range.py", line 68, in <module>
    dis = cmath.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)
TypeError: only length-1 arrays can be converted to Python scalars

尝试过的代码:


import math
import cmath
import numpy as np

cj = cmath.sqrt(-1)
pi2 = 2 * cmath.pi
c = 3e8
fc = 200e6
Xc = 1e3
Yc = 0
Y0 = 100
L = 400
theta_c = cmath.atan(Yc / Xc)
L_min = max(Y0, L)
lamda = c / fc
Xcc = Xc / np.power(np.cos(theta_c),2)
duc = (Xcc * lamda) / (4 * Y0)
mc = 2 * math.ceil(L_min / duc)
uc = duc * np.arange(-mc / 2, mc/2)
k = pi2 / lamda

yn = [0, 70, 66.2500, -80]
fn = [1, 1, 1, 1]
ntarget = 4
s = np.zeros((1, mc))

for i in np.arange(ntarget):
    dis = cmath.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)
    s = s + np.multiply(fn[i] * np.exp(-cj * 2 * k * dis), (abs(uc) <= L))

变量'dis'的预期结果值为1x214 double,变量's'的预期结果值为1x214 complex double

【问题讨论】:

    标签: python numpy square-root elementwise-operations


    【解决方案1】:

    试试dis = np.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)

    cmath.sqrt 作用于标量,而不是数组。您必须使用像numpy.sqrt() 这样的数组运算来获取数组中每个值的平方根。

    注意:这将创建形状为(214,)dis,它仍可用于设置s,但如果您希望dis(1,214),您可能需要在末尾添加.reshape(1, 214)我建议的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多