我一直在尝试找到一种与Excel的Solver相似的方法,在该方法中我可以为要收敛的函数指定特定的值。我不想要最小或最大的优化。
例如,如果我的功能是:
f(x) = A^2 + cos(B) - sqrt(C)
我想要f(x)= 1.86,是否有Python方法可以迭代A,B和C的解决方案以使其尽可能接近1.86? (给出目标值可接受的误差吗?)
答案 0 :(得分: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