Convert a python list into function

613 views Asked by At

I am doing some numerical analysis whereby I have a series of python lists of the form

listn = [1, 3.1, 4.2]

I want to transform these into functions mapped onto a domain between x_0 and x_1, so I can pass the function object to a higher order function that I am using to analyse the data. (Outside the specified domain, the function is chosen to be zero). The function produced needs to be continuous for my purposes, and at the moment I just returning a pieces wise linear function.

I have come up with the convoluted solution below, but there must be a nicer way of doing this in a few lines??

def to_function(array_like, x_0=0, x_1=1):
    assert x_1 > x_0, "X_0 > X_1"
    def g(s, a=array_like, lower=x_0, upper=x_1):

        if lower < s <= upper:
            scaled = (1.0*(s-lower) / (upper - lower)) * (len(a) - 1)
            dec, whole = math.modf(scaled)
            return (1.0 - dec) * a[int(whole)] + dec * a[int(whole + 1)]
        else:
            return 0

    return g

 b = to_function([0, 1, 2, 3, 4, 5], x_0=0, x_1=5)
 print b(1)
 print b(2)
 print b(3)
 print b(3.4)
1

There are 1 answers

0
jme On BEST ANSWER

Will scipy's 1d interpolation functions work?

import numpy as np
from scipy.interpolate import interp1d

x = y = np.arange(5)
f = interp1d(x,y, kind="linear", fill_value=0., bounds_error=False)

print f(0)
print f(2)
print f(3)
print f(3.4)

Which gives:

1.0
2.0
3.0
3.4