First time here? Check out the FAQ!

Ask Your Question
3

Indexed family of functions

asked 13 years ago

jdc gravatar image

I want to create a finite (but large-ish) sequence of symbolic functions f_0(x), f_1(x), etc. (up to, say, f_1000(x)). I can do this for any one function by typing something like: f_4 = function('f_4', nargs=1) Short of doing this 1000 times, how can I do this? (For various reasons, I prefer having the subscript be part of the function's name rather than as a second variable.)

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
3

answered 13 years ago

kcrisman gravatar image

Usually my preferred way to do something like this is use a string formatting substitution. There may be an open ticket for making such things easier, but for now I'd do

sage: for k in range(1001):
    function('f_%s'%k,nargs=1)

The percent signs are telling you to append a string, and that the string will the string from the int k, respectively.

I don't think you have to use the f=function('f') syntax in this case; someone correct me if that's not true.

Preview: (hide)
link

Comments

Ah, that's helpful. I was doing such string tricks in other contexts, but I wasn't able to do that for the "y_0 =" part of "y_0 = function('y_0'...)". If that part is unnecessary, that bypasses the main obstacle.

jdc gravatar imagejdc ( 13 years ago )

if you want to grab all the functions in a list, you can do my_list.append(function('f_%s'%k,nargs=1))

pang gravatar imagepang ( 13 years ago )
2

answered 13 years ago

parzan gravatar image

It's good to know the exec function - a powerful tool for "code generation":

sage: for k in range(1001):                                             
....:     exec("f_%d = lambda x:sin(%d*x)"%(k,k))
....:     
sage: f_11(2)
sin(22)

I don't know what are the risks of using it (sometimes with great power comes great nagging about "bad programming habits", the most famous example is 'goto' commands).

"exec" also has a less powerful brother "eval", which does not help for your needs, but is also good to know (being less powerful he is probably less dangerous).

Preview: (hide)
link

Comments

Ooo... that's good. Yes, I was trying to do with eval to no avail.

jdc gravatar imagejdc ( 13 years ago )

Glad to help. I found a post about these matters: http://lucumr.pocoo.org/2011/2/1/exec-in-python/

parzan gravatar imageparzan ( 13 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: 13 years ago

Seen: 627 times

Last updated: Sep 10 '11