Skip to content

Instantly share code, notes, and snippets.

@tkf
Created February 24, 2017 08:50
Show Gist options
  • Save tkf/1711d292bd7369b97f7b4ecd930dd10b to your computer and use it in GitHub Desktop.
Save tkf/1711d292bd7369b97f7b4ecd930dd10b to your computer and use it in GitHub Desktop.
Simplify `expr` assuming `x` is positive.
import sympy
def recfactor(expr, deep=False):
"""Recursively factorize `expr` including additive terms."""
if isinstance(expr, (sympy.Mul, sympy.Add)):
cls = type(expr)
return cls(*[
recfactor(a, deep=deep).factor(deep=deep)
for a in expr.args
])
else:
return expr
def simplify_with_pos(expr, x,
f=lambda e: recfactor(e.expand().cancel()).simplify()):
"""Simplify `expr` assuming `x` is positive."""
y = sympy.Dummy(positive=True)
return f(expr.subs(x, y)).subs(y, x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment