Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hard integral to lambda function with lambdify

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.

Here is my code:

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
like image 529
lukas kiss Avatar asked May 22 '16 20:05

lukas kiss


People also ask

What is Lambdify?

The lambdify function translates SymPy expressions into Python functions. If an expression is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify acts like a lambda function, except it converts the SymPy names to the names of the given numerical library, usually NumPy.

What lambda function does in Python?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

What is a lambda programming?

Lambda provides a programming model that is common to all of the runtimes. The programming model defines the interface between your code and the Lambda system. You tell Lambda the entry point to your function by defining a handler in the function configuration.


2 Answers

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

The result is

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

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

like image 170
asmeurer Avatar answered Sep 20 '22 06:09

asmeurer


Finally, i find next solution for this. I look around this and find out that return lambda is function. and when you call it with a number it return object (Integarl).

So i can call evalf() to this object and it will return a number. Like this:

import sympy as sp
import numpy as np
x = sp.symbols('x')
f = sp.lambdify(x,sp.integrate(t**t,(t,0,x)))
def return_number(z):
    return f(z).evalf()
return_number(2) #return 2.83387674524687

It works.

like image 39
lukas kiss Avatar answered Sep 20 '22 06:09

lukas kiss