# [Numpy-discussion] numpy.vectorize fails, howto avoid hardcoding parameters?

Alex Kraus alex_work@live...
Mon Aug 2 14:35:56 CDT 2010

Hi,

I am trying to create a function that calculates the integral of another function. The integral function should later be used in scipy.optimize.leastsq(f, ...), so ideally it should have the format:

def f(x, *param)

so that it works for a variable number of parameters. While my code works for a fixed number of parameters I cannot get it to work with a variable number of parameters. It seems that numpy.vectorize fails here.

Is there a different/better way to do this?

import numpy as np

def integrand_function(x, a, b, c):
result = a*x**2 + np.exp(b*x) + np.cos(a*c)
return result

def define_integral(f, lower, upper):
assert(lower < upper)

def function(a, b, c):
result = quad(f, lower, upper, args=(a, b, c))[0]
return result
return np.vectorize(function)

def integrand_function_param(x, *param):
a, b, c = param
result = a*x**2 + np.exp(b*x) + np.cos(a*c)
return result

def define_integral_param(f, lower, upper):
assert(lower < upper)

def function(a, *param):
print(param)
result = quad(f, lower, upper, args=(a, param))[0]
return result
return np.vectorize(function)

a = np.array([1,2,3,4])

print(integrand_function(1,2,3,4))
# 21.9400368894

f = define_integral(integrand_function, 0.0, 2.0)
print(f(a, 1,2))
# [  8.22342909  10.41510219  16.30939667  16.7647227 ]

print(integrand_function_param(1,2,3,4))
# 21.9400368894

fp = define_integral_param(integrand_function_param, 0.0, 2.0)
print(fp(a, 1,2))
# ValueError: mismatch between python function inputs and received arguments

# fp should later be used in scipy.optimize.leastsq(fp, ...

Any help is very appreciated!
Alexander