python - 使用 python 求解嵌套函数(循环方程)?

标签 python python-3.x numpy sympy

是否可以使用 python 来查找嵌套函数的局部最大值/最小值?

例如f(a,b) = a*5/(a-b) 并嵌套它们 -> f( f( f(a, b), b ), b)

嵌套需要动态创建,例如在 for 循环中:

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

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

这很简单,但是我可以从中得到一个方程,然后使用Numpy/Sympy/SciPy或其他东西来查找给定输入范围的本地最大值/最小值

谢谢!

最佳答案

首先得到你的方程相当简单

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)

给出

simplified nested function

然后您可以计算导数并找到零的位置,如下所示

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

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

对我来说,这给出了(a,0)。不幸的是,当计算此时的粗麻布矩阵时,如下所示:

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

我们得到零矩阵

  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.

参见https://en.wikipedia.org/wiki/Second_partial_derivative_test

因此,如果您想证明这些是最大值/最小值,您必须进一步调查。但我相信这超出了您的要求。

关于python - 使用 python 求解嵌套函数(循环方程)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68518002/

相关文章:

python - 如何制作一个迭代超过 1500 万条记录的 for 循环,节省空间?

python - 4D numpy 数组上的矩阵乘法

python : Halton and Hammersley quasi random sequences

python - python 的 argparse 错误

python - 为什么我的函数只能看到我的一些全局变量?

python - 在 docx 中按顺序处理对象

python - 对每对字段执行计算

python - 如何在 pygame 中创建矩形变量而不绘制它们?

python - 为什么 '12345' .count ('' ) 返回 6 而不是 5?

python - 不使用循环计算numpy中多个多项式的根