# Indexed family of functions

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

Sort by ยป oldest newest most voted

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.

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.

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

( 2012-01-17 08:09:07 +0200 )edit

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

more

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

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

( 2011-09-19 02:59:37 +0200 )edit