Home > database >  Iteratively generate restriction of multivariate function using Python
Iteratively generate restriction of multivariate function using Python

Time:09-03

I'm trying to write a function that generates the restrictions of a function g at a given point p.

For example, let's say g(x, y, z) = 2x 3y z and p = (5, 10, 15). I'm trying to create a function that would return [lambda x : g(x, 10, 15), lambda y: g(5, y, 15), lambda z: g(5, 10, z)]. In other words, I want to take my multivariate function and return a list of univariate functions.

I wrote some Python to describe what I want, but I'm having trouble figuring out how to pass the right inputs from p into the lambda properly.

def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restriction = lambda x : g(p[0], p[1], ..., p[i-1], p[x], p[i 1], .... p[-1])
        restrictions.append(restriction)
    return restrictions

Purpose: I wrote a short function to estimate the derivative of a univariate function, and I'm trying to extend it to compute the gradient of a multivariate function by computing the derivative of each restriction function in the list returned by restriction_generator.

Apologies if this question has been asked before. I couldn't find anything after some searching, but I'm having trouble articulating my problem without all of this extra context. Another title for this question would probably be more appropriate.

CodePudding user response:

try something like this:

def foo(fun, p, i):
    def bar(x):
        p[i] = x
        return fun(*p)
    return bar

and

def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restrictions.append(foo(g, p, i))
    return restrictions

CodePudding user response:

Since @bandicoot12 requested some more solutions, I will try to fix up your proposed code. I'm not familiar with the ... notation, but I think this slight change should work:

def restriction_generator(g, p):
    restrictions = []
    for i in range(len(p)):
        restriction = lambda x : g(*p[: i], x, *p[i 1:])
        restrictions.append(restriction)
    return restrictions

Although I am not familiar with the ... notation, if I had to guess, your original code doesn't work because it probably always inputs p[0]. Maybe it can be fixed by changing it from p[0], p[1], ..., p[i-1] to p[0], ..., p[i-1].

  • Related