I have a given function
def unnorm(x, alpha, beta):
return (1 + alpha * x + beta * x ** 2)
Then I integrate to find the normalization constant in the range and turn it into a lambda function that takes the same parameters as unnorm. Now, to create a suitable object, I combine the functions as follows:
def normalized(x, alpha, beta):
return unnorm(x, alpha, beta) * norm(x, alpha, beta)
That's fine and all, but still repeating and pulling names out of the global namespace.
How can I combine the two functions in a cleaner way without overwriting the parameters? for instance
def normalized(func, normalizer):
return func * normalizer
Full code:
import sympy
import numpy as np
import inspect
def normalize_function(f, xmin, xmax):
"""
Normalizes function to PDF in the given range
"""
fx_args = inspect.getfullargspec(f).args
symbolic_args = sympy.symbols(fx_args)
fx_definite_integral = sympy.integrate(f(*symbolic_args), (symbolic_args[0], xmin, xmax))
N = sympy.lambdify(expr = 1 / fx_definite_integral, args = symbolic_args)
return N
def unnorm(x, alpha, beta):
return (1 + alpha * x + beta * x ** 2)
norm = normalize_function(unnorm, -1, 1)
def normalized(x, alpha, beta):
return unnorm(x, alpha, beta) * norm(x, alpha, beta)
x = np.random.random(100)
print(normalized(x, alpha = 0.5, beta = 0.5))