# Can I define a function from a list of values?

Hello,

I am doing numerical integration. If I define the resulting function as a list of values, I have to keep track of both the number of values and the distance between them. This also makes showing the domain on a plot more annoying. Could I instead define a function object from the list of values? In other words, I need an array whose index is not necessarily integer. And I need to be able to plot it over a range.

Thanks!

edit retag close merge delete

Could you be more specific? Are the points uniformly spaced? Do you need to interpolate the values of the function? If you use floats for indices in, say, a dictionary, rounding errors will cause trouble, so I don't see how you could use non-integer indices...

Sort by » oldest newest most voted

Just after posting my other answer, I noticed that sage does include functionality for generating 3D plots from lists of data: see list_plot3d. Perhaps by looking at the code you can see what interpolation function is being used, and use that instead of the naive interpolation wrote above.

more

The best idea I can come up with is to write a new function which interpolates between the values in your list. Here's one easy (and probably too slow) example using linear interpolation:

def interpolate_num_func(x, num_dict):
if x in num_dict.keys():
return num_func[x]

K = num_dict.keys()
K.sort()

# outside the range of inputs, return the first or last value
if x < K:
return num_dict[K]
if x > K[-1]:
return num_dict[K[-1]]

# step through the known values until we find the two which x is between
for i in range(1,len(K)-1):
A = num_dict[K[i]]
B = num_dict[K[i+1]]
if x > K[i] and x < K[i+1]:
t = (x-K[i])/(K[i+1]-K[i])
return t*A + (1-t)*B # interpolate linearly


Now let's make a dict of data to plot: the keys are 'inputs' -- random numbers between 0 and 1; the values are 'outputs' -- random numbers between 0 and 10.

rand_dict = dict((random(),randrange(0,10)) for a in range(15))


And now plot the function:

var('t')
plot(lambda t: interpolate_num_func(t,rand_dict),t,0,1)

more