Search code examples
pythonlambdasympyphysicslambdify

Lambdify-ing an expression with several variables using a single lambda x


Imagine you have the following sympy expression:

'1.0 * H * L * * 3 * W * *2'

which contains the sp.Symbols variables=[H, L and W].

if this expression is lambdify-ed using sp.lambdify([sp.Symbol(vari) for vari in variables],'1.0 * H * L * * 3 * W * *2') you obtain a <function _lambdifygenerated(H, L, W)>.

However, I need to obtain a <function _lambdifygenerated(x)> where H=x[0], L=x[1], and W=x[2].

I have tried to xreplace{H: 'x[0]', W: 'x[1]', L: 'x[2]'} directly on the original expression '1.0 * H * L * * 3 * W * *2' and then lambdify with x as lambda.

This didn't work, but even if it would work after some tries I feel it is not the way to go.

Does anyone have any advice on how to deal with this?

Thank you very much!


Solution

  • You can preprocess the expression to replace all symbols with an IndexedBase, which you can think of as an array:

    from sympy import *
    L, H, W = symbols("L H W")
    expr = 1.0 * H * L**3 * W**2
    
    variables = [L, H, W]
    x = IndexedBase("x")
    # substitution dictionary
    d = {v: x[i] for i, v in enumerate(variables)}
    expr = expr.subs(d)
    print(expr)
    # out: 1.0*x[0]**3*x[1]*x[2]**2
    
    f = lambdify(x, expr)
    import inspect
    print(inspect.getsource(f))
    # out:
    # def _lambdifygenerated(Dummy_22):
    #     return 1.0*Dummy_22[0]**3*Dummy_22[1]*Dummy_22[2]**2