我目前正在制定一项涉及整改的计划。可以进行复杂集成的唯一模块是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
”)。
即。
function([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
如果您需要查看我的完整代码以了解此代码中的任何其他功能,请询问,我很乐意提供它!
答案 0 :(得分:4)
据我了解,您的代码使用SymPy生成符号表达式。这些不是Python意义上的函数,因为它们无法被调用。因此,它们不能直接用作quad
的第一个参数。 SymPy提供了lambdify
方法,将表达式包装到函数中:
quad(lambdify(x, expr), 0, 1)
此处expr
可以是包含变量x
的任何符号表达式,例如expr = 4*x**6 + 2*x + 5
。