Search code examples
pythonpython-3.5difference-equations

How to solve real life difference equations using python


I want to solve a difference equation using python.

y = x(n - 1) - (0.5(x(n-2) + x(n))

x here is a long array of values. I want to plot y with respect to another time sequence array t using Plotly. I can plot x with t, but I am not able to generate the filtered signal y. I have tried the code below, but it seems I'm missing something. I am not getting the desired output.

from scipy import signal
from plotly.offline import plot, iplot
x = array(...)
t = array(...) # x and t are big arrays 
b = [-0.5, 1, -0.5]
a = 0
y = signal.lfilter(b, a, x, axis=-1, zi=None) 
iplot([{"x": t, "y": y}])

However, the output is something like this.

>>>y
>>> array([-inf, ...,  nan])

Therefore, I am getting a blank graph.

UPDATE with examples of x and t (9 values each):

x = [3.1137561664814495,
 -1.4589810840917137,
 -0.12631870857936914,
 -1.2695030212226599,
 2.7600637824592158,
 -1.7810937909691049,
 0.050527483431747656,
 0.27158522344564368,
 0.48001109260160274]

t = [0.0035589523041146265,
 0.011991765409288035,
 0.020505576424579175,
 0.028935389041247817,
 0.037447199517441021,
 0.045880011487565042,
 0.054462819797731044,
 0.062835632533346342,
 0.071347441874490158]

Solution

  • It appears that your problem is defining a = 0. When running your example, you get the following warning from SciPy:

    /usr/local/lib/python2.7/site-packages/scipy/signal/signaltools.py:1353: RuntimeWarning:
    
    divide by zero encountered in true_divide
    
    [-inf  inf  nan  nan  nan  inf -inf  nan  nan]
    

    This division by zero is defined by value a. If you look at the documentation of scipy.signal.lfilter, it points out the following:

    a : array_like The denominator coefficient vector in a 1-D sequence. If a[0] is not 1, then both a and b are normalized by a[0].

    If you change a = 0 to a = 1 you should get output you desire, although do consider that you might want to apply data normalization by a different factor.