Elias Fizesan
Elias Fizesan

Reputation: 305

Sympy very slow at solving equations using solve

I am currently trying to solve an equation for T but unfortunately I am unable to get a solution due to the program running for too long. Is there a way to speed up the time taken to solve the equation?

Code:

Psat_scale = 101325/760

Zi, a, b, c, T, P, VF = symbols('Zi a b c T P VF')

Ki = (exp(a-(b/(T+c)))*Psat_scale)/P
RR = 0

# Costants
P_val = 1
z_vals = [0.4, 0.6]
a_vals = [15.9008, 16.0963]
b_vals = [2788.51, 3346.65]
c_vals = [-52.36, -57.84]

# Part 2
for i in range(2):
  Ki_val = Ki.subs(a, a_vals[i]).subs(b, b_vals[i]).subs(c, c_vals[i]).subs(P, P_val)
  temp_RR_numerator = z_vals[i]*(Ki_val-1)
  temp_RR_denominator = 1+(Ki_val-1)*0
  RR += (temp_RR_numerator/temp_RR_denominator)

RR_equ = Eq(RR, 0)

print(solve(RR_equ, T, simplify=True))

Upvotes: 1

Views: 609

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

The reason that solve is slow is because it converts floats to rationals by default and then here it ends up trying to solve a very large polynomial equation. If you pass rational=False then it will be faster but will not give a solution:

print(solve(RR_equ, T, simplify=True, rational=False))
...
NotImplementedError: multiple generators [exp(2788.51/(T - 52.36)), exp(3346.65/(T - 57.84))]
No algorithms are implemented to solve equation -1.0 + 0 + 429133787.110874*exp(-2788.51/(T - 52.36)) + 782687755.282661*exp(-3346.65/(T - 57.84))

The solve function is for finding analytic solutions but your equation is unlikely to have an analytic solution:

In [4]: RR_equ
Out[4]: 
                         -2788.51                      -3346.65     
                         ─────────                     ─────────    
                         T - 52.36                     T - 57.84    
-1.0 + 429133787.110874⋅ℯ          + 782687755.282661⋅ℯ          = 0

Probably what you want to use is something like nsolve but that doesn't work in this case because the equation is ill-conditioned due to the very large exponential terms. From a quick look at the plot of the log of the lhs it doesn't actually look like this particular equation has any real solutions though (assuming that's what you want).

Upvotes: 1

Related Questions