Skip to content
Advertisement

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

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement