Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to get all discontinuities of a function in a certain domain with sympy?

Given an expression in sympy, is there a way to find all discontinuities in a given interval? For instance, given 1/(x^2-1) from -2 to 2, it would return -1 and 1. It doesn't have to be symbolic. A numerical solution may actually work better for my purposes.

like image 206
sgfw Avatar asked Sep 25 '22 20:09

sgfw


2 Answers

You can use the singularities module for this.

In [ ]: from sympy import *  
In [ ]: init_printing()
In [ ]: x = symbols('x')
In [ ]: singularities(1/(x**2 - 1), x)
Out[ ]: (-1, 1) # A tuple of SymPy objects

Reference: http://docs.sympy.org/latest/modules/calculus/index.html#sympy.calculus.singularities.singularities

like image 147
Kshitij Saraogi Avatar answered Oct 10 '22 18:10

Kshitij Saraogi


I don't think that there's any specific method in SymPy to do this; it might be very difficult to do in full generality (i.e. for any possible function, in any number of variables, including those with infinite discontinuities).

If you're working with relatively simple expressions in one real variable, such as the example in your question, then one approach could be to compute the expression as a ratio of two expressions and then solve the denominator expression.

>>> expr
1/(x**2 - 1)
>>> n, d = expr.as_numer_denom()
>>> sympy.solve(d)
[-1, 1]

Another small example:

>>> expr2 = 1/(sympy.sin(x)) + 4/(x**2 - 3)
>>> expr2
1/sin(x) + 4/(x - 3)
>>> n, d = expr2.as_numer_denom()
>>> sympy.solve(d)
[0, -sqrt(3), sqrt(3), pi]

Obviously in this case SymPy does not list every multiple of pi as a solution; you'll have to process the list to generate solutions that lie in your desired domain.

like image 2
Alex Riley Avatar answered Oct 10 '22 19:10

Alex Riley