Home > Net >  SymPy lambdify gives wrong result, while *.subs gives the accruate one
SymPy lambdify gives wrong result, while *.subs gives the accruate one

Time:03-29

Sorry for bothering you with this. I have a serious issue and now im on clock to solve it, so here is my question.

I have an issue where I lambdify a quantity, but the result of the quantity differs from the ".subs" result, and sometimes it's way off, or it's a NaN, where in reality there is a real number (found by subs)

Here, I have a small MWE where you can see the issue! Thanks in advance for ur time

import sympy as sy
import numpy as np
##STACK
#some quantities needed before u see the problem
r       = sy.Symbol('r', real=True)
th      = sy.Symbol('th', real=True)
e_c     = 1e51
lf0     = 100

A       = 1.6726e-24 



#here are some  quantities I define to go the problem
lfac    = lf0 2
rd      = 4*3.14/4/sy.pi/A/lfac**2 
xi      = r/rd #rescaled r


#now to the problem: 

#QUANTITY
lfxi    = xi**(-3)*(lfac 1)/2*(sy.sqrt( 1   4*lfac/(lfac 1)*xi**(3)   (2*xi**(3)/(lfac 1))**2) -1)

#RESULT WITH SUBS
print(lfxi.subs({th:1.00,r:1.00}).evalf())
#RESULT WITH LAMBDIFY
lfxi_l = sy.lambdify((r,th),lfxi)
lfxi_l(0.01,1.00)
##gives 0

CodePudding user response:

The issue is that your mpmath precision needs to be set higher!

By default mpmath uses prec=53 and dps=15, but your expression requires a much higher resolution than this for it

# print(lfxi)
3.0256512324559e 62*(sqrt(1.09235114769539e-125*pi**6*r**6   6.74235013645028e-61*pi**3*r**3   1) - 1)/(pi**3*r**3)
...
from mpmath import mp
lfxi_l = sy.lambdify((r,th),lfxi, modules=["mpmath"])
mp.dps = 125
print(lfxi_l(1.00,1.00))
# 101.999... result

CodePudding user response:

Changing a couple of the constants to "modest" values:

In [89]: e_c=1; A=1

The different methods produce essentially the same thing:

In [91]: lfxi.subs({th:1.00,r:1.00}).evalf()
Out[91]: 1.00000000461176

In [92]: lfxi_l = sy.lambdify((r,th),lfxi)

In [93]: lfxi_l(1.0,1.00)
Out[93]: 1.000000004611762

In [94]: lfxi_m = sy.lambdify((r,th),lfxi, modules=["mpmath"])

In [95]: lfxi_m(1.0,1.00)
Out[95]: mpf('1.0000000046117619')
  • Related