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
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.
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)'
Related
I have a function f(x) = 1/x^2 and I evaluate the integral from 0 to 1 using scipy.integrate.quad. scipy.integrate.quad is an adaptive integration routine and I would like to know in which regions of [0,1] is the function f evaluated. So, for which values of x is the function f called when making an estimate of the integral?
I'm thinking of using a global variable and appending the x values called to it to keep track of the which x values get used. However, I'm not too familiar on how to do this and any help would be greatly apprecaited, thanks.
The plan is to then plot a histogram to see what regions in the interval [0,1] are evaluated the most.
You could use a decorator class that saves each value x before evaluating the function:
class MemoizePoints:
def __init__(self, fun):
self.fun = fun
self.points = []
def __call__(self, x, *args):
self.points.append(x)
return self.fun(x, *args)
#MemoizePoints
def fun(x):
return 1 / x**2
quad(fun, a = 1e-6, b = 1.0)
Then, fun.points contains all the x values for which the function f was evaluated.
Here, the decorator #MemoizePoints is just syntactic sugar for
def fun(x):
return 1 / x**2
fun = MemoizePoints(fun)
I have a function that takes a vector input, e.g.
f(x) = x[0]*x[1]
I want a function that takes this function and creates a new function:
g(x,y) = x*y
fcn_translator(f)
# intelligent code here
return g
Does anyone know how to do this? Has this been done before. The reason for this question is that I have a python package that optimizes a function of the form f(x,y...) but the function that I'm calling acts on a vector.
Looks like you want a function that takes two parameters, combines them into a vector, and calls f:
def g1(x, y):
return f([x, y])
As a more general solution, the function g2 takes any number of parameters, combines them into a vector, and calls f:
def g2(*x):
return f(x)
Finally, since the first two elements of the vector are required for f, this function takes at least two parameters:
def g3(x, y, *rest):
return f((x, y) + rest)
Dear python Stackoverflow users,
I want to add gaussian functions in a loop as it can be done with integer with the += sign. But I have no idea how to reasign a function value within a loop.
I have tried something like:
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def f(x):
return 0
for i in xdata:
f(x) = f(x) + gaussian(x,i,20)
But I obtained the message "SyntaxError: can't assign to function call"
How could I make this work?
Thanks!
As per my comment:
Replace f(x) in your code by y and replace def f(x): return 0 by y = 0.
You replied:
Ok, it works! Then a function can be defined only with a letter, without mentioning the variable!
That’s not really what’s going on. You are not defining a function. Your desired use of f(x) is not a function. The function f you defined does only one thing:
def f (x):
return 0
The function will always return 0. Once the function is defined like that, it cannot be changed (without replacing it by another function).
What you want to do is collect a function result—but not the result of f but the result of gaussian. Or actually, you want to collect all the results of the gaussian function calls and sum them up.
So what you do is create a variable which you add your results to, which as such represents the sum of those function calls.
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
y = sum(gaussian(x, i, 20) for i in xdata)
f(x) return a result, so it is as you say 0 = 12, for example... That will throw an error, because '=' is assignment operator, so at left of it, you should only have a variable (or a constant for first assignment...).
So maybe you wanted to do:
y = f(x) + gaussian(x,i,20)
But I don't want why you want to do a "+=", because it is only for variables... And your function always returns 0. So you might just say, instead of
def f(x):
return 0
simply
y = 0
and then, tell after in the loop
y += gaussian(x, i, 20).
Or if you want to build a curve, you can use an array.
There is also an other error:
x IS NOT DEFINED in your loop (defined in two functions, but only as local vars)
I should probably start by saying that I am relatively new to python, but I have coded in java and Matlab before.
In python, the code
def func(f):
return f
g = func(cos)
print(g(0))
gives the result
>1.0
as g now is defined as the cosine function.
I want to write a function that calculates the derivative of any provided function using a finite difference approach. The function is defined as
def derivator(f, h = 1e-8):
and would like to achieve the follwing:
g = derivator(cos)
print(g(0)) # should be about 0
print(g(pi/2)) # should be about -1
At the moment my derivator function looks like this
def derivator(f, h = 1e-8):
return (f(x+h/2)-f(x-h/2))/h
which definitely is wrong, but I am not sure how I should fix it. Any thoughts?
Your current derivator() function (which should probably be called differentiator()) uses an undefined variable x and would return a single value, if x were defined--the value of f'(x). You want to return a function that takes an x value. You can define an inner function and return it:
def fprime(x):
return (f(x+h/2)-f(x-h/2))/h
return fprime
Because you don't use that function anywhere else, though, you can use lambda instead, which is also shorter:
return lambda x: (f(x+h/2)-f(x-h/2))/h
The only thing PEP 8 says about lambdas is that you should not assign the result of the lambda to a variable, then return it:
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # Don't do this!
return fprime
Make an inner function inside your derivator function and return it:
from math import cos, pi
def derivator(f, h = 1e-8):
def g(x):
return (f(x+h/2)-f(x-h/2))/h
return g
g = derivator(cos)
print(g(0)) # 0.0
print(g(pi/2)) # -0.999999993923
f and h will be part of the closure of the returned function.
You can also return a lambda expression to make it one line:
return lambda x: (f(x+h/2)-f(x-h/2))/h
I am reading through A Concise Introduction to Programming in Python by Mark J.Johnson and I stumbled upon a piece of code that uses darts to estimate the area under the graph. The code is working perfectly fine but I am getting confused as to why you would pass a function as a parameter if you could just call the function anyway.
from random import uniform
from math import exp
def area(function , a ,b ,m ,n = 1000 ): #changed parameter for better understanding
hits = 0
total_area = m * (b-a)
for i in range(n):
x = uniform(a,b)
y = uniform(0,m)
if y <= function(x):
hits += 1
frac = hits / float(n)
return frac * total_area
def f(x):
return exp(-x**2)
def g(x): #new function
return exp(-x**2) + 2
def main():
print area(f,0,2,1)
print area(g,0,2,1)
main()
He states that passing a function as a parameter is 'powerful' but I can't see why?
f is but one graph function. It is not the only function that you could define to create a graph.
You can also define other functions:
def g(x):
return 2 * x ** 2 + x + 5
and pass this into area() without having to alter that function. area() is generic enough to calculate the area of different graph functions, and all you need to do is pass in the graph function to have it calculate that area.
Had you hardcoded f instead of using a parameter, you could no longer do that.
I think the answer should be obvious, especially in this case: You can write a generic function for something like calculus integration that works on any function you pass in. You can modify the function you're integrating by supplying a new function. Likewise for other operations like graphing.