# Can sage compute the inverse of a function?

Hello Sage community,

is it possible to compute the inverse of a function in one variable with sage? So say I have

f(x) = log(x)


and I want to compute

f.inverse()


Thank you Paul

edit retag close merge delete

Sort by » oldest newest most voted

Here is a stupid method:

var('x,y')
f(x) = log(x)
g(x) = solve(x == f(y), y).rhs()
print g


Here is a compilation from several scattered sources:

more

Thank you Kelvin! Your 'solve' method works for me. As for the Mathematica method, by using Sage I hope to avoid having to pay for a Mathematica license.

1

Sage aims to be an alternative to Mathematica (and the other M's). Replicating the functionality of those software has motivated the development of several features in Sage (case in point: revolution_plot). I mentioned Mathematica's InverseFunction because it is one of those features for which Sage does not have an obvious counterpart. Someone might want to look into this.

@Kelvin Li: Why don't you open a Trac ticket for this :) if one doesn't already exist, which I think it may. Thanks!

It may also be useful to note that you can make assumptions about the domain using the assume function since a given function f(x) may not have an inverse on its entire domain, or it may have different inverse functions on different subdomains:

sage: f(x) = x^2
sage: assume(y<0)
sage: solve( x == f(y), y).rhs()
-sqrt(x)
sage: forget()
sage: assume(y>0)
sage: solve( x == f(y), y).rhs()
sqrt(x)

more

The trick is to use the roots method of the given symbolic expression as follows:

Example 1

sage: var('y')
y
sage: f(x) = log(x) - y
sage: f.roots(x)
[(e^y, 1)]
sage: f.roots(x, multiplicities=False)
[e^y]


Example 2

f does not need to be callable.

sage: var('y')
y
sage: f = log(x) - y
sage: f.roots(x)
[(e^y, 1)]


Example 3

Use a helper function so that the expression "hacking" can be contained neatly:

sage: def symbolic_inverse(f, x):
....:    y = SR.var('y')
....:    g = (f - y).roots(x, multiplicities=False)
....:    return [expr.subs(y=x) for expr in g]
....:
sage: symbolic_inverse(log(x), x)
[e^x]
sage: symbolic_inverse(sin(x), x)
[arcsin(x)]
sage: symbolic_inverse(x, x)
[x]
sage: symbolic_inverse(x^2, x)
[-sqrt(x), sqrt(x)]
sage: var('c')
c
sage: symbolic_inverse(c^3, c)
[1/2*(I*sqrt(3) - 1)*c^(1/3), 1/2*(-I*sqrt(3) - 1)*c^(1/3), c^(1/3)]


Note that multiple inverses are all listed and that any variable can be used. However, only one branch is returned for the inverse of sin(x), namely arcsin(x).

If an inverse cannot be found or does not exist, a RuntimeError error is raised:

sage: symbolic_inverse(x + sin(x), x)
(... Traceback ...)
RuntimeError: no explicit roots found

more