0

I am trying to solve this equation for lambda λ using python. the equation is here

in that, For i in the index column, P_0, c, t, D, F are given in the dataframe as below:

dataframe

Given r = constant = 0.6, Excel Solver can solve the equation for lambda easily. But I am new to python and I have been struggling with python sympy to find a way to solve it. Please help! Thanks alot!

Edit: this is my dataframe dataframe

This is my python code. It takes forever to run while Excel Solver took less than 1 second so I think there must be something wrong with it.

import sympy as sy
x = sy.Symbol('x', real =True)
coupon = max(cal_lambda['c'])
r = 0.6
F = 100
P = max(cal_lambda['P_O'])
component1 = 0
component2 = 0
for i1, i2 in zip(cal_lambda['T'],cal_lambda['D']):
    component1 += coupon*np.e**(-x*i1*1/100*i2)
    component2 += r*np.e**(-x*0.5*1/100*i2)
component3 = F*np.e**(-x*cal_lambda['T'].tail(1)*cal_lambda['D'].tail(1))
Equation = sy.Eq(component1 + component2 + component3,P)
sol = sy.solve(Equation)
print(sol)
dntt3007
  • 1
  • 1

1 Answers1

1

Here's a simple version of a loop that solves equations for each values for i1 and i2.

You'd need to define the function for your equation and then define symbolic variables. After that read constants from your dataframe and then solve the function

>>> from sympy import symbols, Eq, solve
... x = symbols('x')
... for i1,i2 in zip(range(5),range(5)):
...   eq1 = Eq(x*i1 -5*i2*x + 6)
...   sol = solve(eq1, dict=True)
...   print(sol)
[]
[{x: 3/2}]
[{x: 3/4}]
[{x: 1/2}]
[{x: 3/8}]
paloman
  • 160
  • 9
  • my python code is as follow: import sympy as sy x = sy.Symbol('x', real =True) coupon = max(cal_lambda['c']) r = 0.6 F = 100 P = max(cal_lambda['P_O']) component1 = 0 component2 = 0 for i1, i2 in zip(cal_lambda['T'],cal_lambda['D']): component1 += coupon*np.e**(-x*i1*1/100*i2) component2 += r*np.e**(-x*0.5*1/100*i2) component3 = F*np.e**(-x*cal_lambda['T'].tail(1)*cal_lambda['D'].tail(1)) Equation = sy.Eq(component1 + component2 + component3,P) sol = sy.solve(Equation) print(sol) But it doesn't seem to work (take forever to run) – dntt3007 Jul 24 '20 at 13:31
  • I wrote my code based on @paloman code. I just broke the equation into 3 components as it is too complex. no error occured (yet). but it takes forever to run. this is only small sample of a big data. If a small sample is that troublesome, i dont dare to think about the large data... – dntt3007 Jul 24 '20 at 13:50