Yashdeep Singh
Yashdeep Singh

Reputation: 31

Converting sympy function to lambda function

I've been trying to convert my sympy function variable which looks like this:-

(atan(๐‘งโˆ’3/๐‘ฅ)+2.66602685430536โ‹…10โˆ’6)^2+(atan(๐‘งโˆ’2/๐‘ฅ)โˆ’0.0896686524911619)^2+(atan(๐‘งโˆ’1/๐‘ฅ)โˆ’0.16739555984988)^2

Function expression

I've been trying to use lambdastr and lambdify for this purpose. In the following way:-

s = lambdastr((x,z),function)
lam_func = lambdify([x,z],s,myfuncs)

But keep getting this error:-

AttributeError: 'Symbol' object has no attribute 'atan'

I figured out it was because the lambdastr adds math module for the atan function in the following way:-

s = lambdastr((x,z),function)
print(s)

lambda x,z: ((math.atan((z - 3)/x) + 2.66602685430536e-6)2 + (**math.atan((z - 2)/x) - 0.0896686524911619)2 + (**math.atan((z - 1)/x) - 0.16739555984988)**2)

So, I implemented the atan separately like this:-

s = lambdastr((x,z),function)
s = s.replace("math.atan","tan_inv")
def tan_inv_impl(x):
    return math.atan(x)
myfuncs = {"tan_inv":tan_inv_impl}
lam_func = lambdify([x,z],s,myfuncs)

This does give me a lambda function but it doesn't seem to work

lam_func(1,1)

Gives an error:

in _lambdifygenerated(x, z)

1 def _lambdifygenerated(x, z):
----> 2 return (Lambda((x, z), (tan_inv((z - 3)/x) + 2.66602685430536e-6)**2 + (tan_inv((z - 2)/x) - 0.0896686524911619)**2 + (tan_inv((z - 1)/x) - 0.16739555984988)**2))

NameError: name 'Lambda' is not defined

Can someone help me with this issue?

Thanks

Upvotes: 3

Views: 638

Answers (1)

smichr
smichr

Reputation: 19115

How about using Lambda?

>>> from sympy import Lambda
>>> function  # defined as you described
(atan(z - 3/x) + 2.66602685430536e-6)**2 + (atan(z - 2/x) -           
0.0896686524911619)**2 + (atan(z - 1/x) - 0.16739555984988)**2
>>> f = Lambda((x,z), function)
>>> f(1,1).n()
2.01953558567067

Upvotes: 1

Related Questions