gpt4 book ai didi

python - 将 Matlab @ 翻译成 Python 代码(RuntimeWarning : invalid value encountered in true_divide )

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:04 24 4
gpt4 key购买 nike

我正在将 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 ID 一直说我不应该使用 lambda 函数,而应该定义一个函数。谁能告诉我为什么?我能够将“乐趣”转化为一种功能;我尝试过:

def fun(LL):
f(LL, Sad, n, u_mean)
return(f)

res = scipy.optimize.minimize(fun=fun, x0=LL0)

但它不起作用。如果有人能告诉我原因,那就太好了。

感谢您的帮助

关于python - 将 Matlab @ 翻译成 Python 代码(RuntimeWarning : invalid value encountered in true_divide ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com