I am building a class for constructing a certain type of approximating function (mathematical function). This approximating function will be a linear combination of a given number of basis functions, which I store in a list, and it will return a scalar. A method of the class needs to update my approximating function in each iteration, by multiplying each basis function with a scalar (different scalars for different basis functions), and forming the sum. In other words, I need to update my approximating function by forming a linear combination of the basis functions and setting my approximating function to this unevaluated sum of functions.
The default basis for this class is a polynomial basis, which I’ve implemented with NumPy’s poly1d class. The way I form the linear combination is currently
sum(self.basis[i]*self.coeffs[i] for i in range(self.dim))
where (obviously) self.basis is the list of basis functions, self.coeffs is the list of scalars to multiply with the basis functions, and self.dim is the number of basis functions. This works for the poly1d class, but not, for example, if I use a basis like:
basis1 = [lambda x: float(x), lambda y: float(y)**2]
or
def x(y):
return y
def x2(y):
return y**2
basis2 = [x, x2]
Basis1 gives me the error
TypeError: only length-1 arrays can be converted to Python scalars
Basis2 gives me the error
TypeError: unsupported operand type(s) for *: 'function' and 'numpy.float64'
Likewise, using
sum(itertools.imap(operator.mul, self.basis, self.lambdas))
works for the poly1d basis, but not for the other bases above, and gives the same error messages.
So my question is: how do I form a linear combination of unevaluated functions in Python (using or not using NumPy)?
A quick way to combine the function basis with the coefficients is a python dictionary:
This prints:
Then you will need to derive a Dict subclass to handle the mathematical operations that you need.
Even simpler would be to keep the coef and function lists separate and operate just on the coef list until you need to evaluate.