I am trying to use sympy help me simplify some equations and check whether two formula are equivelant. But in one case I find it quite confusing when handling Abs(cos(inc))/sqrt(cos(inc)**2). I expect the output should be 1 but the original expression is given back.
from sympy import simplify, parse_expr,Symbol
inc=Symbol('inc',positive=True,real=True)
exp_str='1*Abs(cos(inc))/sqrt(cos(inc)**2)'
exp=parse_expr(exp_str)
tmp=exp.subs("Abs(cos(inc))/sqrt(cos(inc)**2)","1")
which gives the following output:
Abs(cos(inc))/sqrt(cos(inc)**2)
instead of simply 1.
Note that I already restrict the inc to be positive real number, I wonder what to do to make it work and understand why the formula is not simplified.
Some reference about the difference of expression, function is also welcomed.
You forgot to tell parse_expr
that you already defined your symbol inc
, which can be done by providing the local_dict
keyword argument to this function, which maps string names to already defined symbols. By doing so, your expression automatically simplifies to 1:
from sympy import simplify, parse_expr,Symbol
inc=Symbol('inc',positive=True,real=True)
exp_str='1*Abs(cos(inc))/sqrt(cos(inc)**2)'
exp=parse_expr(exp_str, local_dict={'inc': inc})
exp
# out: 1
Edit for clarity: when you execute your original code:
exp_str='1*Abs(cos(inc))/sqrt(cos(inc)**2)'
exp=parse_expr(exp_str)
Here, parse_expr
is going to create missing symbols, which are the ones parse_expr
was not made aware of. So, parse_expr
sees 'inc'
, it decides it is a symbol and creates it like this:
inc_parse_expr = Symbol("inc")
Note that inc_parse_expr
doesn't have any assumptions, and the resulting expression cannot be simplified further. That's why you were getting an expression out of the parsing.
To prevent this behavior, you have to provide the local_dict
keyword argument.