Reputation: 31
I want to do something like this
def gaussian(x, amp):
return amp * exp(-(x-cen)**2 /wid)
I want to substitute just amp and x and obtain an equation as output
for example:
gaussian(1,3)
3 * exp(-(1-cen)**2 /wid)
as output.
Can I do this for a couple of lists, in one several values of amplitude an in the other their respective x's
Upvotes: 2
Views: 66
Reputation: 610
I am not sure what you mean by "I need an equation". Do you need something you can evaluate? Then probably you can return a lambda object, and then you can evaluate that. Or you can use closure something like:
import math
def gaussian(x, amp):
def _gauss( cen,wid):
return amp * math.exp(-(x-cen)**2 /wid)
return _gauss
g = gaussian(10,1)
print g(2,4)
g now is a callable function where x and amp has been replaced so you need to pass only cen and wid
The reason why this work is because the internal function, _gauss, gets evaluated every time you call the wrapper function, doing so the function will be evaluated using the argument passed by the parent function and be used there as "static". Since then you return a function you can evaluate that and pass all the params left, this is a common technique for when a library forces you to have parameterlles callbacks. Only draw back is more expensive then a simple function call, that is to generate the child function, not to evaluate it.
Upvotes: 4
Reputation: 446
I would convert your return
to a string:
def gaussian(x, amp):
return str(amp) + '* exp(-(' + str(x) + '-cen)**2 /wid)'
This should return the value you want:
gaussian(1,3)
returns
'3 * exp(-(1-cen)**2 /wid)'
Upvotes: 1