pythonpython-3.xmathsympy

How Can I Find the Range of a Function in Sympy


I'm getting started with Sympy and I have some questions. I have a function and I would like to find the domain (all possible x values for f) and the range (all possible y values for f) of that function, I have already been able to get the function domain using continuous_domain but I can't find a way of getting the range.

This is an example function:

from sympy import *
from sympy import Symbol, S
from sympy.calculus.util import continuous_domain

x = Symbol("x")
f = sin(x)/x
domain = continuous_domain(f, x, S.Reals)
print(domain)

Is there any way in Sympy to get the range of a function, if not, how would you accomplish this task?


Solution

  • From the same util.py you can import function_range and use that. In general, solve f(x) = y for x and find the continuous domain of that.

    >>> solve(x**2 - 1 - y,x)
    [-sqrt(y + 1), sqrt(y + 1)]
    >>> [continuous_domain(i,y,S.Reals) for i in _]
    [Interval(-1, oo), Interval(-1, oo)]
    

    But that requires that you be able to solve the expression...which is not always possible as for sin(x)/x (and that is why function_range will fail for that).