title: How to find a solution for a non-linear equation in python using ifelse defined function
body: <p>I am encountering a problem solving a nonlinea equation using nsolve from the python simpy package, this problem was easily solved in R, below the code I use in R and what I am trying in python:</p>
  
  <p>R : </p>
  
  <pre><code>library(dplyr)
  library(plyr)
  sol = adply(df,1, summarize,
               solution_1 = uniroot.all(function(x)(eval(parse(text=as.character(FX),df))),lower = -10000, upper = 10000, tol = 0.00001))
  
  
  </code></pre>
  
  <p>In Python: </p>
  
  <pre><code>from sympy import Symbol, solve, nsolve
  from sympy.parsing.sympy_parser import parse_expr
  import pandas as pd
  
  def ifelse(cond,yes,no):
      if (cond):
          return(yes)
      else: 
          return (no)   
  
      data = {'A': [10,20,30],
          'B': [20,10,40],
          'FX': ["ifelse(A+B+x&lt;0,0,A+B-x)","ifelse(A+B+x&lt;0,0,A*B-x)","ifelse(A+B+x,A*B-x,A+B-x)"]}
  df = pd.DataFrame(data)
  
  x = Symbol("x", real=True)
  cols= df.columns
  print(cols)
  for _, row in df.iterrows():
      print(nsolve(parse_expr(row["FX"],local_dict=dict({c:row[c] for c in cols}, **{'x':x,"ifelse":ifelse}) ),x,0))
  
  </code></pre>
  
  <p>The expected solution is: [30,200,30]</p>
  
  <p>But the following error was returned:</p>
  
  <blockquote>
    <p>TypeError: cannot determine truth value of Relational</p>
  </blockquote>
  
  <p>Because the code in python can't evaluate A+B-x, I don't know how to change the code so that it evaluates the expression with the initial value of x.</p>
  
  <p>Any ideas on how to work around this problem?</p>