gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:31:30 26 4
gpt4 key购买 nike

我目前正在做一个涉及整改的程序。唯一可以进行复杂集成的模块是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com