First time here? Check out the FAQ!

Ask Your Question
0

Can I define a function from a list of values?

asked 14 years ago

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!

Preview: (hide)

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 ( 14 years ago )

2 Answers

Sort by » oldest newest most voted
0

answered 14 years ago

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.

Preview: (hide)
link
0

answered 14 years ago

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)
Preview: (hide)
link

Comments

Thanks! This is exactly what I was looking for.

chaesloc gravatar imagechaesloc ( 14 years ago )

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: 14 years ago

Seen: 1,048 times

Last updated: Dec 16 '10