【问题标题】:Trying to integrate function gives "loop of ufunc does not support argument 0 of type Symbol"尝试集成函数给出“ufunc 循环不支持符号类型的参数 0”
【发布时间】:2020-12-09 17:26:33
【问题描述】:

我的包裹:

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

现在我想定义另一个函数,它与x 集成了Hh 函数。我尝试这样做:

def I(n, c, a, b, d):
    return sci.quad(np.exp(a*x) * Hh(n, b*x - d), c, 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,1,1)

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

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

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

【问题讨论】:

  • sci 和 scs 是什么?
  • 我编辑我的帖子并添加包
  • 什么是参数的例子?
  • 为什么不能使用sympy集成功能?
  • 您正在尝试使用无法使用符号的函数。我的建议是将x定义为符号,手动编码x的范数、平方根和指数函数,然后利用sympy.integrate()整合Hh()的输出。跨度>

标签: python numpy math integration


【解决方案1】:

您可以按如下方式确定每个条件的不定积分:

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))

可能有一个可以处理 norm 的 sympy 函数(在 n == 0 时使用),但我从未使用过(你会看到我刚刚将公式编码)。 此外,在处理符号定义的指数函数时,请务必使用sp.exp() 而不是math.exp() 或np.exp()。

如果您需要确定定积分,请查看: https://docs.sympy.org/latest/modules/integrals/integrals.html

我没有在您的 else 声明中添加以节省时间,但上述内容仍然适用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2021-12-07
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    相关资源
    最近更新 更多