尝试集成函数给出“ ufunc循环不支持Symbol类型的参数0”

问题描述

我的包裹:

from pylab import plt
import pandas as pd
import numpy as np
import sympy as sy
import matplotlib.pyplot as plt
import datetime as dt
from pylab import mpl
import scipy.integrate as sci
import scipy.stats as scs
import pandas_datareader as web
import statsmodels.api as sm
import scipy.optimize as spo
from yahoo_fin import options
from dawp import *
import math
import sys
import yfinance as yf

我定义一个函数

def Hh(n,x):
    if n == -1:
        return np.exp(-x**2 / 2)
    elif n == 0:
        return math.sqrt(2*math.pi) * scs.norm.cdf(-x)
    else:
        return (Hh(n-2,x) - x * Hh(n-1,x)) / n

现在,我想定义另一个相对于Hh集成x函数函数。我尝试这样做:

def I(n,c,a,b,d):
    return sci.quad(np.exp(a*x) * Hh(n,b*x - d),np.inf)

但我收到此错误

AttributeError                            Traceback (most recent call last)
AttributeError: 'Symbol' object has no attribute 'exp'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-73-796991ea4106> in <module>
----> 1 I(1,1,1)

<ipython-input-72-0a67e7ee1499> in I(n,d)
      1 def I(n,d):
----> 2     return sci.quad(np.exp(a*x)*Hh(n,b*x-d),np.inf)

TypeError: loop of ufunc does not support argument 0 of type Symbol which has no callable exp method

对于x,我应该更改什么以获得正确的结果?

解决方法

您可以确定每个条件的不定积分,如下所示:

import numpy as np
import sympy as sp

x = sp.symbols('x')

def Hh(n):

    if n == -1:
        fx = sp.exp(-x**2 / 2)

    elif n == 0:
        fx = ((2*np.pi)**(1/2)) * (sp.exp((-x**2)/2) / (2*np.pi)**(1/2))

    return fx

print (sp.integrate(Hh(n=0),x))

可能存在一个可以处理规​​范的sympy函数(在n == 0时使用),但是我从未使用过(您会看到我已经在其中编写了公式)。 此外,在处理符号定义的指数函数时,请确保使用sp.exp()而非math.exp()np.exp()

如果需要确定定积分,请看一下: IComparable interface

为了节省时间,我没有放入您的else语句,但是以上内容仍然适用。