解决仅size-1数组可以转换为Python标量错误

Rya*_*ree 2 python math numpy function

我有以下函数,但是当我运行程序时,只有“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
Run Code Online (Sandbox Code Playgroud)

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

Nil*_*ner 7

您不能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
Run Code Online (Sandbox Code Playgroud)