3

I define 2 sympy functions f, g, s.t. g is inverse of f:

import sympy as sy

g = sy.Function('g')

class f(sy.Function):
    def inverse(self, argindex=1):
        return g

x, y = sy.symbols('x y')
print sy.solve(y - f(x), x) # [g(y)] - correct

But if I try to evaluate f(g(x)) sympy doesnt simplify this:

print f(g(x))               # f(g(x))
print f(g(x)).doit()        # f(g(x)) - why not x?
print f(g(x)).simplify()    # f(g(x)) - why not x?

Question: how to say to sympy that f(g(x)) is just x?

1 Answer 1

3

inverse isn't implemented to do that. I opened https://github.com/sympy/sympy/issues/10487 for it. Ideally what I write below should work by default.

You can easily make it work by defining _eval_simplify, like

class f(sy.Function):
    def inverse(self, argindex=1):
        return g

    def _eval_simplify(self, ratio, measure):
        if isinstance(self.args[0], self.inverse()):
            return self.args[0].args[0]
        return self

If you have many classes you want to do this with you can put that in a superclass.

In [30]: f(g(x))
Out[30]: f(g(x))

In [31]: f(g(x)).simplify()
Out[31]: x

Or if you prefer for doit() to do it you can define doit().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.