Search code examples
pythonsympyset-intersectionlambdify

How to lambdify an Intersection


I am inverting a function with the invert_real from sympy.solvers.solveset, because neither solve nor solveset can do it for some reason. The result is an Intersection and seems to be correct.

I now want to use it for numeric calculations. When I try it with .subs it works fine, but when I try to lambdify I get

NameError: name 'Intersection' is not defined

I already found that I need to pass a source for Intersection in the modules= of lambdify. But I can't find a working source.

Here is a code example:

from sympy import *
from sympy.solvers.solveset import invert_real

x, y = symbols('x,y')

expr = 1 - exp(-18000000*x)

res_alg = invert_real(expr, y, x)[1]
print("res_alg: ", res_alg)

res_1 = res_alg.subs(y, 0.5)
print("res_1: ", res_1)

res = lambdify(y, res_alg, "numpy")
print(res, res(0.5))

Solution

  • The easiest is to ignore Intersection and lambdify only the set that is its second argument.

    res = lambdify(y, next(iter(res_alg.args[1])), "numpy")
    print(res(0.5))
    

    Prints 3.850817669777474e-08.

    Here, res_alg.args is the list of arguments of Intersection. args[1] picks {-log(-y + 1)/18000000}. next(iter(...)) picks the first element from that set, so that the lambdified function returns a float instead of a set.

    If you pass a value for which there is no real solution, such as res(1.5), the output is nan.