flappingwings
flappingwings

Reputation: 65

Use Lambdify for multiple symbolic variables

The python script below evaluates the first term in the expression, 4.939e-3xAxB+8.7989 at (A,B) = (1.0,1.0):

 import sympy
 from sympy import *

 A = sympy.Symbol(A)
 B = sympy.Symbol(B)
 F = 4.939e-3*A*B+8.7989
 G = str(F).split("+")[0]
 H = lambdify([A,B], G, "numpy")
 print H(1,1)

The ouput is: 0.004939

Now the code below aims to achieve the same objective:

A = sympy.Symbol(A)
B = sympy.Symbol(B)
F = 4.939e-3*A*B+8.7989
G = str(F).split("+")[0]
H = lambdify(A, G, "numpy")
I = lambdify(B, H(1), "numpy")
print I(1)

But this returns the error: NameError: global name 'B' is not defined

Can someone kindly explain this?

Upvotes: 4

Views: 10243

Answers (1)

Wrzlprmft
Wrzlprmft

Reputation: 4434

You are conflating strings and symbols at multiple instances. The only reason that any of this works at all is that SymPy applies sympify to many inputs (sympify("A")==Symbol("A")) and Python’s duck typing. Specifically, G is a string, when it should be a symbolic expression, and all first arguments passed to lambdify are strings or lists of strings, when they should be symbols or lists thereof.

A clean version of your first code would be:

from sympy.abc import A,B
import sympy

G = 4.939e-3*A*B # now this is a symbolic expression, not a string
H = lambdify( [A,B], G, "numpy" )
print(H(1,1))

And the same for your second code:

from sympy.abc import A,B
import sympy

G = 4.939e-3*A*B # now this is a symbolic expression, not a string
H = lambdify( A, G, "numpy" )
I = lambdify( B, H(1), "numpy" )
print(I(1))

Upvotes: 6

Related Questions