Python matplotlib错误:提供的函数未返回有效的

2024-10-02 00:38:29 发布

您现在位置:Python中文网/ 问答频道 /正文

from __future__ import division
import functools
import warnings
import numpy as np
import scipy as sp
from scipy import integrate
from numpy import exp, pi
import matplotlib.pyplot as plt

warnings.simplefilter("ignore", np.ComplexWarning)


def legendrePoly(a,n):

    def integrand(t):
        return ( ((a + exp(2j*pi*t))**2 - 1)/(2*exp(2j*pi*t)) )**n

    return sp.integrate.quad(integrand,0,1)[0]


basisDim = 6
legendreBasis = [functools.partial(legendrePoly, n=i) for i in range(basisDim)]

integrand = [lambda x,i=i: exp(x) * legendreBasis[i](x) for i in range(basisDim)]
normalizingConst = [lambda x,i=i: legendreBasis[i](x)**2 for i in range(basisDim)]
basisCoeff = [sp.integrate.quad(integrand[i],-1,1)[0]
             /sp.integrate.quad(normalizingConst[i],-1,1)[0] for i in range(basisDim)]

approxPoly = lambda x: sum(basisCoeff[i]*legendreBasis[i](x) for i in range(basisDim))


t = np.arange(-1, 1, 1e-3)
plt.plot(t,exp(t),'b')
plt.plot(t,approxPoly(t),'r')
plt.show()

我用勒让德多项式作为指数函数多项式逼近的基础。我也用柯西的积分公式来计算它们,而不是直接从numpy导入它们。在

在定义approxPoly之前(包括定义approxPoly)一切正常,并且approxPoly返回我输入的任何输入的预期值。但由于某些原因,当我试图绘制approxPoly(t)时,它返回错误:提供的函数没有返回有效的float。在

此错误似乎表明,当legendreBasis中的函数调用scipy.integrate.quad,那里出了点问题,但是如果是这样的话,那么approxPoly就不起作用了,但是如果你在-1和1之间的2000个点上手动计算,然后画出这些点,一切都很好,但这不正是什么吗plt.绘图当它试图绘制我的函数时会怎么做?在

回溯:

^{pr2}$

Tags: infromimportnumpyforasrangeplt
1条回答
网友
1楼 · 发布于 2024-10-02 00:38:29

scipy.integrate.quad不集成返回数组的函数。这意味着当您尝试调用approxPoly(t)时,t会被传递,直到它在这个函数中结束:

def legendrePoly(a,n):

    def integrand(t):
        return ( ((a + exp(2j*pi*t))**2 - 1)/(2*exp(2j*pi*t)) )**n

    return sp.integrate.quad(integrand,0,1)[0]

integrand返回一个数组,sp.integrate.quad阻塞。同样的问题在代码中多次出现。一切似乎都是假设标量参数编写的。在

您可以通过调用approxPoly上的^{}来解决此问题:

^{pr2}$

然后NumPy将分别对t的每个元素调用approxPoly。在

相关问题 更多 >

    热门问题