【问题标题】:Can Python optimize my function inputs to get a target value?Python 可以优化我的函数输入以获得目标值吗?
【发布时间】:2018-07-11 05:53:21
【问题描述】:

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

例如,如果我的函数是:

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

我想要 f(x) = 1.86,是否有 Python 方法可以迭代 A、B 和 C 的解决方案以尽可能接近 1.86? (给定目标值可接受的错误?)

【问题讨论】:

标签: python optimization scipy convergence


【解决方案1】:

您需要一个根查找算法来解决您的问题。只需要一个小的转换。为 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

【讨论】:

  • 这太完美了!非常感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2023-03-08
  • 2019-09-16
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
相关资源
最近更新 更多