python - scipy.integrate.quad() 不使用 lambda

标签 python lambda scipy integration

我目前正在制作一个涉及整改的程序。唯一可以进行复杂集成的模块是 Scipy 及其 scipy.integrate.quad() 命令。但是,在我的代码中,我需要一个代表函数本身的变量,因为在校正过程中最终会使用更多不同的函数,这些函数是通过使用前面的方程导出的。我见过的有关该命令的每个来源要么涉及 lambda,要么创建输出方程的定义。手动输入方程。所以,我的问题是,有没有什么方法可以在不这样做的情况下集成它?这是我的代码:

import scipy                                                   
import sympy
from scipy.integrate import quad

def rectify(smallestterm, nextsmallestterm, poly, coef, exp):
   test = rectification(coef,exp)
   a = quad(test, smallestterm, nextsmallestterm)
   print(a)
   a = a[0]
   dist = a/2
   return dist     
def test(x):
   return rectification(coef, exp)
def rectification(coef, exp):
   u = Poly(lint(coef,exp)) #Generated Equation
   b = u.all_coeffs()
   poly = b
   c = len(poly) - 1
   exponents = []
   while c + 1 > 0:
       exponents.append(c)
       c = c - 1
   poly = function(poly,exponents)   #Generated Equation in a form that can actually be used and identified as a function.
   return sqrt(1+(pow(diff(poly),2)))

其中,coef 是多项式的前导系数列表,exp 是多项式的前导指数列表。本质上,它们都将间接组合在另一个定义中,function(coef, exp)(其代码未显示),输出多项式(变量“poly”) .

函数([2,4,5],[1,6,0])输出

4*x**6 + 2*x + 5

这段代码(在函数代码之上)不起作用,因为它不允许我使用变量“a”来表示整个函数,因为它只将“a”识别为函数本身。 所以,lambda 在我的情况下不起作用。我不能简单地做这样的事情:

import scipy
import sympy
from scipy.integrate import quad
poly = 2*x**5 + 5*x**4 - 4*x**2 + 10   #Some complicated polynomial
d = diff(poly) #differential of polynomial
a = sqrt(1+(pow(d,2)))
e = quad(a, 1, 5)
e = e[1]/2
return e

如果您需要查看我的完整代码以了解此代码中的任何其他功能,请询问,我很乐意提供!

最佳答案

据我了解,您的代码使用 SymPy 生成符号表达式。这些不是 Python 意义上的函数,因为它们无法被调用。所以它们不能直接用作quad的第一个参数。 SymPy 提供 lambdify将表达式包装到函数中的方法:

quad(lambdify(x, expr), 0, 1)

这里expr可以是任何带有变量x的符号表达式,例如expr = 4*x**6 + 2*x + 5

关于python - scipy.integrate.quad() 不使用 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528681/

相关文章:

python - 使用 flask 和外部上下文/cronjobs 发送电子邮件

entity-framework-4 - Entity Framework 4.1 - 选择

python - 确保 Python 计算器万无一失

c# - 如何将 lambda 表达式翻译成英文?

amazon-web-services - python获取本地时区?

python - 将大型稀疏矩阵转换为 COO 时出错

python - 在 Python 中对齐两个数据集

python - LinAlg错误: SVD did not converge in Linear Least Squares when trying polyfit

python - 如何制作Python 2轴 slider

python - 为什么 Django 不承认我的类变量?