【问题标题】:Nested loop -TypeError: only size-1 arrays can be converted to Python scalars嵌套循环 -TypeError:只有大小为 1 的数组可以转换为 Python 标量
【发布时间】:2021-12-19 05:47:24
【问题描述】:

我正在尝试使用两个不同的变量找到最大值:

    import numpy as np
    import matplotlib.pyplot as plt
    from math import pi, sqrt
    
    i =.5
    l = .01
    u = 4*pi*10**-7
    
    angle = np.linspace(0,pi/2,20)
    d = np.linspace(0,.5, 50)

    B = []

    for ang in angle:
            for dis in d:
                x = (u*i*np.cos(ang))/(pi*sqrt((l/2)**2 + d**2))
                B.append(max(x))

但是,它一直给我"TypeError: only size-1 arrays can be converted to Python scalars"

我什至不确定这是什么意思。

【问题讨论】:

    标签: python numpy loops math nested


    【解决方案1】:

    您的问题是由试图获取向量作为输入的math.sqrt() 函数引起的:与 l 相关的项是标量,而与 d 相关的项是向量。通常,Python 会尝试将标量值添加到向量中的每个条目,从而生成向量。如果这是您想要的,您可以只需将数学包的 sqrt 替换为 np.sqrt()

    让我们看看为什么会这样:

    math.sqrt() 只接受标量作为输入。如果数组的大小为 1,它也可以工作,然后将其转换为标量:

    >>> math.sqrt(np.array([4]))
    2.0
    

    在您的情况下尝试过,但失败了,因为括号中的术语是一个大小大于 1 的向量。您可以在一个更简单的示例中进行尝试:

    >>> math.sqrt(np.array([9, 25]))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: only size-1 arrays can be converted to Python scalars
    

    在这些情况下,您可以只使用numpys sqrt 方法而不是maths 方法:

    >>> np.sqrt(np.array([9, 25]))
    array([3., 5.])
    

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2018-07-22
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 2019-06-19
      • 2020-08-09
      相关资源
      最近更新 更多