FST - Finite Differences

239 days ago by mpaul

Finite Differences

- Michel Paul

Here is a function that will find the differences between each pair of consecutive terms in a list:

def differences(L): return [b-a for (a,b) in zip(L[:-1],L[1:])] 
       

Here is a list of random numbers:

whatever = [randint(1,20) for i in range(10)] whatever 
       
differences(whatever) 
       
differences(_) 
       

The differences between random items will also be random.

See what happens with the differences between pairs of consecutive terms in a list of fibonaccis:

fibos = [fibonacci(i) for i in [0..10]] fibos 
       
differences(fibos) 
       
differences(_) 
       

The differences between consecutive fibonaccis will themselves be fibonaccis!

See what happens with the differences between consecutive odd numbers:

[2*n+1 for n in [0..10]] 
       
differences(_) 
       

Now see what happens with the differences between consecutive squares:

[n^2 for n in [0..10]] 
       
differences(_) 
       

The differences between consecutive squares are consecutive odd numbers!

And so the differences between the differences are:

differences(_) 
       

It took us 2 levels of differences to get a row of constants, and the formula n^2 has degree 2.

It only took us 1 level of differences with the odd numbers, and in that formula n had degree 1: 2n+1.

Here's a list of cubes:

[n^3 for n in [0..10]] 
       
differences(_) 
       
differences(_) 
       
differences(_) 
       

Here we had to find 3 levels of differences before we got a list of constants.

That's the whole point of finding these differences -

  • if the values in the original list come from a polynomial function, then at some point finding differences will terminate in a row of constants,
  • and the degree of the original polynomial will equal the number of levels of differences.

The following cell will create a fourth degree polynomial function:

a,b,c,d,e = [randint(0,5) for i in range(5)] f(x) = a*x^4 + b*x^3 + c*x^2 + d*x + e 
       

Here are the values of f(x) for x values between 0 and 10:

[f(x)for x in [0..10]] 
       
differences(_) 
       
differences(_) 
       
differences(_) 
       
differences(_) 
       

It took 4 levels of differences to reach a row of constants.

Here is the original function:

       

Again, a constant row of differences will only occur when f(x) is a polynomial function.

[2^x for x in [0..10]] 
       
differences(_) 
       
differences(_) 
       
differences(_) 
       

In this case the formula was 2^x.  It's not a polynomial.