Ask Your Question
3

Indexed family of functions

asked 2011-09-07 16:10:58 -0500

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

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
3

answered 2011-09-08 03:14:37 -0500

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.

edit flag offensive delete link more

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 ( 2011-09-08 09:10:17 -0500 )edit

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 ( 2012-01-17 01:09:07 -0500 )edit
2

answered 2011-09-10 03:51:09 -0500

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

edit flag offensive delete link more

Comments

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

jdc gravatar imagejdc ( 2011-09-13 05:56:33 -0500 )edit

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

parzan gravatar imageparzan ( 2011-09-18 19:59:37 -0500 )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: 2011-09-07 16:10:58 -0500

Seen: 176 times

Last updated: Sep 10 '11