Ask Your Question
0

Can I define a function from a list of values?

asked 2010-12-16 09:04:22 +0100

chaesloc gravatar image

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 flag offensive close merge delete

Comments

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...

pangard gravatar imagepangard ( 2010-12-16 10:11:44 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
0

answered 2010-12-16 14:26:28 +0100

niles gravatar image

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.

edit flag offensive delete link more
0

answered 2010-12-16 14:24:15 +0100

niles gravatar image

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[0]:
        return num_dict[K[0]]
    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)
edit flag offensive delete link more

Comments

Thanks! This is exactly what I was looking for.

chaesloc gravatar imagechaesloc ( 2010-12-19 20:12:41 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2010-12-16 09:04:22 +0100

Seen: 1,037 times

Last updated: Dec 16 '10