具有函数和 scipy 的多个参数

Multiple arguments with function and scipy

需要使用 scipy 优化器针对 x 优化和最小化以下代码。 问题是它适用于单个参数,但是当函数采用多个值时,它无法处理它。

这段代码运行良好。

from scipy.optimize import root
b = 1
def func(x):
    # result when x = 0, but result equation depends also on b value.
    result = x + b
    return  result

sol = root(func, 0.1)
print(sol.x, sol.fun)

但这行不通.....

b =[ 1, 2, 3, 4, 5]

def func(x, b):
    # result when x = 0, but result equation depends also on b value.
    result = x + b
    return  result

for B in b:
    sol = root(lambda x,B: func(x, B), 0.1)
    print(sol.x, sol.fun)

如何通过b迭代得到结果?

如@hpaulj 所述,root 接受一个 args 参数,该参数将传递给 func。所以,我们可以让脚本更灵活:

from scipy.optimize import root

def func(x, *args):
    result = 0
    for i, a in enumerate(args): 
        result += a * x ** i
    return  result

coeff_list = [(6, 3), (-3, 2, 1), (-6, 1, 2)]


for coeffs in coeff_list:
    sol = root(func, [-4, 4][:len(coeffs)-1], args = coeffs)
    print(*coeffs, sol.x, sol.fun)

输出:

6 3 [-2.] [8.8817842e-16]
-3 2 1 [-3.  1.] [ 1.46966528e-09 -4.00870892e-10]
-6 1 2 [-2.   1.5] [-6.83897383e-14  4.97379915e-14]

初步回答

我不明白你的 lambda 函数的必要性:

from scipy.optimize import root

def func(x):
    # result when x = 0, but result equation depends also on b value.
    result = x + b
    return  result

B =[ 1, 2, 3, 4, 5]

for b in B:
    sol = root(func, 0.1)
    print(b, sol.x, sol.fun)

输出:

1 [-1.] [0.]
2 [-2.] [0.]
3 [-3.] [0.]
4 [-4.] [0.]
5 [-5.] [0.]

我在 scipy documentation 中没有看到任何关于如何将参数传递给 func 的提示。但这种方法也适用于多个参数:

from scipy.optimize import root

def func(x):
    #depending on the parameters, this has 0, 1 or 2 solutions
    result = a * x ** 2 + b * x + c
    return  result

A = range(3)
B = [3, 2, 1]
C = [6, -3, -6]


for a, b, c in zip(A, B, C):
    sol = root(func, [-4, 4])
    print(a, b, c, sol.x, sol.fun)

输出:

0 3  6 [-2. -2.]  [ 8.8817842e-16   0.0000000e+00]
1 2 -3 [-3.  1.]  [ 1.46966528e-09 -4.00870892e-10]
2 1 -6 [-2.  1.5] [-6.83897383e-14  4.97379915e-14]