Python 可以优化我的函数输入以获得目标值吗?

Can Python optimize my function inputs to get a target value?

我一直在尝试找到一种类似于 Excel 的 Solver 的方法,我可以在其中针对要收敛的函数指定一个特定值。我不想要最小或最大优化。

例如,如果我的函数是:

f(x) = A^2 + cos(B) - sqrt(C)

我想要f(x) = 1.86,有没有Python方法可以迭代A、B、C的解,使其尽可能接近1.86? (给定一个可接受的目标值误差?)

您的问题需要求根算法。只需要一个小的转换。求 g(x):

的根

g(x) = A^2 + cos(B) - sqrt(C) - 1.86

使用 scipy.optimize.root, 参考 documentation:

import numpy as np
from scipy import optimize

# extra two 0's as dummy equations as root solves a system of equations 
# rather than single multivariate equation
def func(x):                                        # A,B,C represented by x ndarray
    return [np.square(x[0]) + np.cos(x[1]) - np.sqrt(x[2]) - 1.86, 0, 0]

result = optimize.root(func , x0 = [0.1,0.1,0.1])
x = result.x
A, B, C = x                       
x
# array([ 1.09328544, -0.37977694,  0.06970678])

您现在可以检查您的解决方案:

np.square(x[0]) + np.cos(x[1]) - np.sqrt(x[2])

# 1.8600000000000005