我正在将一个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.
作为回报,我得到的值与我用作暂定值的值相同有人能帮我吗?提前感谢
最终找到了解决方案;我不太确定为什么现在它起作用了——我给同一个变量赋值了两次。不管怎样,这就是我的解决方案:
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 idle一直说我不应该使用lambda函数,而是应该定义一个函数。。有人能告诉我为什么吗?我能够将"乐趣"转化为一种功能;我尝试过:
def fun(LL):
f(LL, Sad, n, u_mean)
return(f)
res = scipy.optimize.minimize(fun=fun, x0=LL0)
但它不起作用。如果有人能告诉我原因就好了。
感谢您的帮助