Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 209819

How to find a solution for a non-linear equation in python using ifelse defined function

$
0
0

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:

R :

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))


In Python:

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<0,0,A+B-x)","ifelse(A+B+x<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))

The expected solution is: [30,200,30]

But the following error was returned:

TypeError: cannot determine truth value of Relational

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.

Any ideas on how to work around this problem?


Viewing all articles
Browse latest Browse all 209819

Trending Articles