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

Time:09-22

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)

enter image description here

CodePudding user response:

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