Reputation: 115
I try to solve a system of equations in python (with sympy) but I get "TypeError: Invalid NaN comparison". The equations are "almost linear" (linear equations but also contains an abs part).
For a function f I try to find 2 points [x0, x1] such that f(x0) = x1 and f(x1) = x0 (so these 2 equations form a system)
I have:
from sympy import *
c = 2
x = Symbol('x', real=True)
f1 = c * (1/2) * (Abs(2*x-1)) # define a function with variable 'x', also Abs func is from sympy if I'm not wrong
x0 = Symbol('x0', real=True)
x1 = Symbol('x1', real=True)
ec1 = Eq(f.subs(x, x0), x1)
ec2 = Eq(f.subs(x, x1), x0)
print(ec1) # 1.0*Abs(2*x0 - 1) = x1
print(ec2) # 1.0*Abs(2*x1 - 1) = x0
sol = solve((ec1, ec2), (x0, x1) ) # AND HERE is the place where the type error appear:
# TypeError: Invalid NaN comparison
How can I fix this error? Or, there are others methods to solve equations like those from above in python?
Upvotes: 0
Views: 595
Reputation: 19029
solve
is not set up to solve systems of Piecewise
equations (which are what the two Abs
-equations are turned into). But if you fold the And
of the system and then solve each of the possible expressions, you can see the solutions:
>>> pw=(piecewise_fold(And(ec1.rewrite(Piecewise), ec2.rewrite(Piecewise))))
>>> for e,co in pw.args:
... s=solve(e.args)
... if co.subs(s):
... print(s)
This gives
{x0: 1.00000000000000, x1: 1.00000000000000}
{x0: 0.600000000000000, x1: 0.200000000000000}
{x0: 0.200000000000000, x1: 0.600000000000000}
{x0: 0.333333333333333, x1: 0.333333333333333}
Upvotes: 1