I need to create a function for an arbitrary number of peaks to pass to a least square fitting routine. For each peak there is an extra term in the function, i.e.
One term with a value at 50 returns a function: f(p, x) = p[0]*50
Two terms with values at 50, 60 returns a function: f(p, x) = p[0]*50 + p[1]*60*x
Three terms with values at 50, 60, 70 returns: f(p, x) = p[0]*50 + p[1]*60*x + p[2]*70*x^2
etc.
A couple of naive attempts are shown below,
def foo(vals):
fn = lambda p, x: 0
i = 0
for v in vals:
fn = lambda p, x : fn(p, x) + p[i] * v * x**i
i += 1
return fn
# Causes a recursion error (I think)
Second attempt ...
def bar(vals):
terms = []
i = 0
for v in vals:
terms.append(lambda x, p: p[i] * v * x**i)
i += 1
def fn(x, p):
tvals = [t(x, p) for t in terms]
sum = 0
for t in terms:
sum = sum + t(x, p)
return sum
return fn
# Generates the wrong values
I suspect that this is a problem with referencing, i.e. Python refers to list declarations etc. but this is a little complicated to untangle - any help would be appreciated!
fnalot ...