问题描述
以下代码需要使用 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,3,4,5]
for b in B:
sol = root(func,0.1)
print(b,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,1]
C = [6,-3,-6]
for a,b,c in zip(A,B,C):
sol = root(func,4])
print(a,c,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]