kpeteL
kpeteL

Reputation: 55

Using python to solve nested functions (reccurring equations)?

Is it possible to use python to find local maxima/minima for a nested function?

For example f(a,b) = a*5 / (a-b) And nesting them -> f( f( f(a, b), b ), b)

The nesting would need to be dynamically created, for example in a for loop:

def f(a,b):
    return a*5 / (a-b)

input = 1
for x in range(3):
    input = f(input, b)

This is easy, but could I get an equation out of it and then using Numpy/Sympy/SciPy or something to find local maxima/minima for given input range?

Thanks!

Upvotes: 2

Views: 501

Answers (1)

Lukas S
Lukas S

Reputation: 3603

First getting your equation is rather simple

import sympy

a, b = sympy.symbols('a, b')

def f(a, b):
    return a*5 / (a-b)

g = a
for x in range(3):
    g = f(g, b)

g = sympy.simplify(g)

gives

simplified nested function

You can then calculate the derivative and find where it is zero like so

dg_a = sympy.diff(function, a)
dg_b = sympy.diff(function, a)

sols = sympy.solve([dg_a, dg_b],[a,b])

For me this gives (a,0). Unfortunately when calculating the hessian matrix at that point like so:

sympy.lambdify([a,b],sympy.matrices.Matrix([[dg_a, dg_b]]).jacobian([a,b]))(a,0)

We get the zero matrix so

  1. If D(a, b) = 0 then the second derivative test is inconclusive, and the point (a, b) could be any of a minimum, maximum or saddle point.

See https://en.wikipedia.org/wiki/Second_partial_derivative_test

So if you wanted to prove those are maxima/minima you would have to investigate further. But I believe that is beyond what you're asking.

Upvotes: 2

Related Questions