我寫了一個代碼,對於r和阿爾法使用SciPy的最小化某個功能。但是我遇到了一個將參數傳遞給函數的問題。minimazing功能,如何將參數傳遞到函數SciPy的
#!/usr/bin/env python
import numpy as np
from scipy.integrate import quad
import scipy.optimize as opt
def integrand(t, alpha, r):
return np.exp(-alpha*(t-r))**2
def my_function(parameters, rho):
alpha = parameters[0]
r = parameters[1]
return quad(integrand, 0, rho, args=(alpha, r))[0]
alpha_0 = 1
r_0 = 1
rho = 5.0
vec_expint = np.vectorize(my_function)
res = opt.minimize(my_function(rho), np.asarray([alpha_0, r_0]), method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})
print(res)
我希望把整合作爲邊界變量。我添加了一個變量rho,並收到以下錯誤消息:
res = opt.minimize(my_function(rho), np.asarray([alpha_0, r_0]), method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})
TypeError: my_function() takes exactly 2 arguments (1 given)
有人能解釋我如何以正確的方式傳遞參數嗎?
我明白了!謝謝你的深刻解釋!這對我幫助很大! – Monica