我正在将Matlab代码转换为python,我被卡在这里。 我认为使用@会创建一个局部变量,对吗? 我试图使用嵌套函数来处理代码,但是在处理其中一个变量时似乎存在问题。
#Code's variable:
#LL0 = first tentative value
#Sad and f = returns of psd estimation via welch's method
#Sad = is the psd of discrete time-series
#f = is an array of the sampled frequencies
#u_mean = is a scalar
% Matlab Code
f = @(LL, Sad, n, U_media)sum((Sad - 4 * n * LL / U_media .* (1 + 70.8 * (n * LL / U_media).^2).^(-5/6)).^2);
fun = @(LL)f(LL, Sad, n, U_media);
LL = fminsearch(fun, LL0);
def f1(LL, Sad, n, u_mean):
a = sum((Sad - 4 * n * LL / u_mean * (1 + 70.8 * (n * LL / u_mean)**2)**(-5/6))**2)
return(a)
f2 = lambda LL, Sad, u_mean, f: f1(LL, Sad, n, u_mean)
fun = lambda LL: f2(LL, Sad, n, u_mean)
LL = scipy.optimize.fmin(func=fun, x0=LL0, maxfun=100000, xtol=1e-6, maxiter=10000, disp=True)
代码正在运行,但是迭代为我提供了此输出
RuntimeWarning: invalid value encountered in true_divide
sum((S_adim - 4 * f * LL / u_mean * (1 + 70.8 * (f * LL / u_mean**2)**(-5/6)))**2)
RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
Warning: Maximum number of iterations has been exceeded.
我得到的价值与我尝试使用的价值相同 谁能帮我?预先感谢
答案 0 :(得分:0)
def f(LL, Sad, n, u_mean):
f = sum((Sad - (4 * n * LL / u_mean) *
((1 + 70.8 * ((n * LL / u_mean) ** (2)))**(-5 / 6)))**2)
return(f)
fun = lambda LL: f(LL, Sad, n, u_mean)
res = scipy.optimize.minimize(fun=fun, x0=LL0)
Lux = res.x
顺便说一句,spyder闲话总是说我不应该使用lambda函数,而应该定义一个函数..有人可以告诉我为什么吗?我能够将“乐趣”翻译成一个函数;我尝试过:
def fun(LL):
f(LL, Sad, n, u_mean)
return(f)
res = scipy.optimize.minimize(fun=fun, x0=LL0)
但是它不起作用。如果有人能告诉我原因,那就太好了。
感谢您的帮助