Ask Your Question

Indexed family of functions

asked 2011-09-07 23:10:58 +0200

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

answered 2011-09-08 10:14:37 +0200

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

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


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 16:10:17 +0200 )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 08:09:07 +0200 )edit

answered 2011-09-10 10:51:09 +0200

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)

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


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

jdc gravatar imagejdc ( 2011-09-13 12:56:33 +0200 )edit

Glad to help. I found a post about these matters:

parzan gravatar imageparzan ( 2011-09-19 02:59:37 +0200 )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


Asked: 2011-09-07 23:10:58 +0200

Seen: 549 times

Last updated: Sep 10 '11