[Tutor] constructing semi-arbitrary functions

spir denis.spir at gmail.com
Tue Feb 18 15:30:30 CET 2014


On 02/17/2014 08:23 PM, "André Walker-Loud <walksloud at gmail.com>" wrote:
> Hello python tutors,
>
> I am utilizing a 3rd party numerical minimization routine.  This routine requires an input function, which takes as arguments, only the variables with which to solve for.  But I don’t want to define all possible input functions, in a giant switch, but rather, if I know I am fitting a polynomial, I would like to just pass a list of parameters and have the code know how to construct this function.
>
> To construct for example, a chisq function, you must pass not only the variables to solve for, but also the data, uncertainties, and perhaps other arguments.  So it requires a little hacking to get it to work.  With the help of my friends and looking at similar code, I have come up with two ways that work under my simple test cases, and I have a few questions about them.
>
> The 3rd party minimizer utilizes the .func_code.co_varnames and .func_code.co_argcount to determine the name and number of variables to minimize.  eg.
>
>> g = lambda x,c_0,c_1: c_0 + c_1 * x
>> g.func_code.co_varnames
> ('x', 'c_0', 'c_1’)
>> g.func_code.co_argcount
> 3
>
> so what is needed is a function
>> def f(c_0,c_1):
>> …#construct chi_sq(c_0,c_1,x,y,…)

What prevents you to make a simple function factory (see example below) is that 
the 3rd party module needs to use func_code.co_varnames & func_code.co_argcount, 
right? If yes, it is indeed annoying... and I have no good solution.

# func factory example:
def poly (*coefs):
     # coefs are here in reverse order for simplicity
     # but we could iterate backward below
     n = len(coefs)
     def f (x):
         y = 0
         for i in range(n):
             y += coefs[i] * x**i
         return y
     return f

# y = 3 + 2*x + 1*x^2
poly3 = poly(3,2,1)
print(poly3(1)) # 6
print(poly3(2)) # 11
print(poly3(3)) # 18

d


More information about the Tutor mailing list