【问题标题】:Solving only size-1 arrays can be converted to Python scalars error仅求解 size-1 数组可以转换为 Python 标量错误
【发布时间】:2021-12-13 18:58:35
【问题描述】:

我有以下函数,但是当我运行程序时,我只有“size-1 数组可以转换为 Python 标量”的错误

import math as math
import numpy as np

def chebs(c, d, n):
    k = np.array(range(n))
    y = ((2*k +1)*np.pi)/(4*(n+1))
    return c*math.sin(y)**2 + d*math.cos(y)**2

有没有办法规避这个错误?我假设它来自我在函数中使用数学?

【问题讨论】:

    标签: python function numpy math


    【解决方案1】:

    您不能将numpy.math. 函数混合使用,只能使用numpy. 函数:

    import numpy as np
    
    def chebs(c, d, n):
        k = np.arange(n)
        y = ((2 * k + 1) * np.pi) / (4 * (n + 1))
        return c * np.sin(y) ** 2 + d * np.cos(y) ** 2
    

    【讨论】:

      【解决方案2】:

      math 中的函数通常需要一个数字作为参数;而numpy 中的函数通常期望从单个数字到多维数组的任何内容,并将数学函数应用于数组中的每个元素。

      例如:

      >>> import math
      >>> import numpy as np
      
      >>> math.sqrt(4)
      2.0
      >>> math.sqrt(25)
      5.0
      >>> np.sqrt(4)
      2.0
      >>> np.sqrt(25)
      5.0
      
      >>> np.sqrt([4,25])
      array([2., 5.])
      
      >>> math.sqrt([4,25])
      TypeError: must be real number, not list
      
      >>> math.sqrt(np.array([4,25]))
      TypeError: only size-1 arrays can be converted to Python scalars
      

      事实证明,包含单个数字的 numpy 数组能够在需要时将自己隐式转换为不带数组的单个数字,所以这是可行的:

      >>> math.sqrt(np.array([[25]]))
      5.0
      

      您收到的错误消息是告诉您“数组y 包含多个数字,因此无法将其转换为单个数字,因此您无法在其上调用math.sin。”

      如果要将math 中的函数应用于列表中的每个元素,可以使用list comprehensionbuiltin function map 来实现。但是请注意,numpy 的全部意义在于在大型数组上非常快速地执行计算,而使用列表推导式或map 将无法实现这一目的。

      >>> list(map(math.sqrt, [4, 25]))
      [2.0, 5.0]
      >>> [math.sqrt(x) for x in [4,25]]
      [2.0, 5.0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2021-12-24
        • 2019-11-11
        • 2021-12-01
        • 2020-11-03
        相关资源
        最近更新 更多