我正在尝试使用Scipy优化以下问题

目前,我已经定义了我的方程,并尝试使用四次函数和最小化来求解方程。
import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize
def g_x(x, cv):
cv2 = np.square(cv)
return (x+1-np.sqrt(np.square(x)+2*cv2*x+1))/(1-cv2)
def g_approx(x, c):
return (c*x)/(1+c*x)
def integrand(x, cv, c):
return g_x(x, cv)-g_approx(x, c)
def minimization_function(c, cv, xm):
return quad(integrand, 0, xm, args=c)
c_0 = 1
cv = 0.6
xm = 15
res = minimize(minimization_function, c_0, method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})在试图解决这个问题时,我会得到以下错误。
scipy\optimize\optimize.py:261, in _prepare_scalar_function(fun, x0, jac, args, bounds, epsilon, finite_diff_rel_step, hess)
257 bounds = (-np.inf, np.inf)
259 # ScalarFunction caches. Reuse of fun(x) during grad
...
132 # Overwriting results in undefined behaviour because
133 # fun(self.x) will change self.x, with the two no longer linked.
--> 134 return fun(np.copy(x), *args)
TypeError: minimization_function() missing 2 required positional arguments: 'cv' and 'xm'因此,我知道在某个时候,我需要给C_v和X_m,因为它们都缺少来解决这个问题,但是,我不知道如何做到这一点。有人能帮助我理解如何在这些方程中定义变量和常数吗?我试过翻阅以前的答案,但我似乎无法让它们发挥作用。
发布于 2022-07-17 07:26:14
quad和minimize都期望有一个带有fun(x, *args)签名的函数。因此,您需要使用lambda表达式包装函数,或者使用args参数。还请注意,quad不返回标量,因此需要从返回的元组中提取整数值:
# ... your other functions and constants here ...
def minimization_function(c, cv, xm):
return quad(lambda x: integrand(x, cv, c), 0, xm)[0]
res = minimize(lambda c: minimization_function(c, cv, xm), c_0)相反,使用args参数,代码如下所示:
# ... your other functions and constants here ...
def minimization_function(c, cv, xm):
return quad(integrandx, 0, xm, args=(cv, c))[0]
res = minimize(minimization_function, c_0, args=(cv, c))PS:没有必要用quad对积分进行数值计算。相反,您可以简单地使用封闭表单表达式(如果不想自己派生它,请参见WolframAlpha )。
https://stackoverflow.com/questions/72998766
复制相似问题