本文介绍了使用lambdify将硬积分转换为lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对函数 Integral(t ** t,(t,0,x))进行lambdize.它可以工作,但是由 lambdify 返回的我的新函数不返回数字,而仅返回 sympy.integrals.integrals.Integral 类.但我不希望这样,我希望它返回一个浮点数.

I would like to lambdify the function Integral(t**t,(t,0,x)). It works, but my new function, which was returned by lambdify, doesn't return a number but only sympy.integrals.integrals.Integral class. But I don't want that, I want it to return a float number.

这是我的代码:

import sympy as sp
import numpy as np
f = sp.lambdify(x,sp.integrate(t**t,(t,0,x)))
print(f(2)) #return Integral(t**t, (t, 0, 2))
#but i want 2.83387674524687

推荐答案

lambdify 不直接支持 scipy.integrate.quad ,但是添加适当的定义并不难.一个人只需要告诉 lambdify 如何打印 Integral :

lambdify doesn't support scipy.integrate.quad directly yet, but it's not difficult to add the appropiate definition. One simply needs to tell lambdify how to print Integral:

def integral_as_quad(expr, lims):
    var, a, b = lims
    return scipy.integrate.quad(lambdify(var, expr), a, b)

f = lambdify(x, Integral(t**t,(t,0,x)), modules={"Integral": integral_as_quad})

结果是

In [42]: f(2)
Out[42]: (2.8338767452468625, 2.6601787439517466e-10)

我们在这里正在定义一个函数 integral_as_quad ,该函数将SymPy Integral 转换为 scipy.integrate.quad 调用,递归地对被积数进行lambd化(如果您有更复杂或符号化的积分限制,那么您也将希望递归地对这些被积数进行lambdize).

What we're doing here is defining a function integral_as_quad, which translates a SymPy Integral into a scipy.integrate.quad call, recursively lambdifying the integrand (if you have more complicated or symbolic integration limits, you'll want to recursively lambdify those as well).

这篇关于使用lambdify将硬积分转换为lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:47