Trying to solve an equation with Sympy, TypeError: cannot create mpf from x

Viewed 36

I'm attempting to solve the equation shown below. For that I have done the following:

from sympy import symbols, Eq, Sum, nsolve
import math 
#this variables are for testing purposes
cr_user = 0.25 
amount_of_days = [0.108219, 0.6082191781]
md_user = 0.6082191781
price_user = 98.37

x, i= symbols("x i")
if len(amount_of_days)% 2 == 0:
    lhs = Sum(cr_user*(math.e**(-x*(md_user-i))), (i, 0.5, 0.5*len(amount_of_days))).doit()
    rhs = Sum(-cr_user*(math.e**(-x*(md_user-i))) - (cr_user+100)*math.e**(-x*md_user) + price_user, (i, 1, 0.5*(len(amount_of_days)-1))).doit()
    print(nsolve(Eq(lhs, rhs),x))
else: 
    lhs = Sum(cr_user*(math.e**(-x*(md_user-i))), (i, 0.5,  0.5*(len(amount_of_days)-1))).doit()
    rhs = Sum(-cr_user*(math.e**(-x*(md_user-i))) - (cr_user+100)*math.e**(-x*md_user) + price_user, (i, 1, 0.5*len(amount_of_days))).doit()
    print(nsolve(Eq(lhs, rhs),x))

I attempt to solve for x, I always get the following error:

raise TypeError("cannot create mpf from " + repr(x))

TypeError: cannot create mpf from x (for line 23)

Basically the picture summarizes the code. The only difference is that I have 2 cases in the code, when len of the list is even and that when is odd. I attempt to solve for x.

3 Answers

I think you are trying to solve the equation: cr_user*(e**(-x*(md_user-i))) = -cr_user*(e**(-x*(md_user-i))) - (cr_user+100)*e**(-x*md_user) + price_user

Which is equivalent to: e**(-x*(md_user-i)) = (cr_user+100)*e**(-x*md_user) - price_user

Which is equivalent to: e**(-x*md_user) = (cr_user+100)*e**(-x*md_user) - price_user

Which is equivalent to: 1 = (cr_user+100) - price_user

Which is equivalent to: price_user = cr_user+100

Which is equivalent to: 98.37 = 0.25+100

Which is equivalent to: 98.37 = 100.25

Which is obviously false.

What should the second nsolve argument be? A: an initial guess for the root.

Giving an initial guess of 0 gives a numerical result which appears to satisfy the equation:

enter image description here

My attempt ( I haven't yet done anything in sympy, so this is my first attempt to use it) was :

lrhs = lhs - rhs  # create a function of x to search where it is zero
print(nsolve(lrhs, x, 0)) # resolve x, use 0 to start with search

and I have got:

0.0480416484284691

Here the code with the outcome checking the equation:

lrhs = lhs - rhs
print(nsolve(lrhs, x, 0))               # 0.0480416484284691
print(lrhs.subs(x, 0.0480416484284691)) # 2.55351295663786e-15
Related