Python中的二维优化(最小化)(使用scipy.optimize)

2024-04-27 10:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图优化(最小化)二维函数E(n,k),定义如下:

error=lambda x,y,w: (math.log(abs(Tformulated(x,y,w))) - math.log(abs(Tw[w])))**2 + (math.atan2(Tformulated(x,y,w).imag,Tformulated(x,y,w).real) - math.atan2(Tw[w].imag,Tw[w].real))**2

其中Tformulated获得如下:

def Tformulated(n,k,w):
    z=1j
    L=1
    C=0.1
    RC=(w*L)/C
    n1=complex(1,0)
    n3=complex(1,0)
    n2=complex(n,k)
    FP=1/(1-(((n2-n1)/(n2+n1))*((n2-n3)/(n2+n3))*math.exp(-2*z*n2*RC)))
    Tform=((2*n2*(n1+n3))/((n2+n1)*(n2+n3)))*(math.exp(-z*(n2-n1)*RC))*FP
    return Tform

Tw是以前计算过的具有复数元素的列表。 我正试图做的是对每个w(用于“error x,y,w….”)的值,我希望最小化x&;y的值的函数“error”。w范围从1到2048。所以,这基本上是一个二维最小化问题。我已经试过编程(尽管我被困在使用什么方法和如何使用它);我的代码如下:

temp=[]
i=range(5)
retval = fmin_powell(error , x ,y, args=(i) , maxiter=100 ,maxfun=100)
temp.append(retval)

即使fmin_powell是正确的方法,我也不确定。


Tags: 函数logerrormathabsrealtwrc
1条回答
网友
1楼 · 发布于 2024-04-27 10:18:45

下面是一个简单的例子:

from scipy.optimize import fmin

def minf(x):
  return x[0]**2 + (x[1]-1.)**2

print fmin(minf,[1,2])

[出局]:

Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 44
         Function evaluations: 82
[ -1.61979362e-05   9.99980073e-01]

这里有一个可能的问题是最小化例程需要一个列表作为参数。所有血淋淋的细节见the docs。不确定是否可以直接最小化复数函数,可能需要分别考虑实部和虚部。

相关问题 更多 >