samedi 30 novembre 2019

Problem updating arrays inside a for loop and if-else statments

Table8.5 trying to implement this table in python.

To obtain the following results: enter image description here

I am currently printing up to the 7th step, then the program ceases to update correctly. Almost there.

I am suspecting the bug to be either with the placement of the global arrays or if-else indentation.

Please help if you could point out the problem and explain how I can avoid it in the future. Thanks

here is the link for more details if needed:https://rodolfoferro.wordpress.com/2017/02/24/nelder-mead-method/.

B=[1.2, 0] #Initial starting points. 
G=[0, 0.8]
W=[0 ,0]

# M(B,G)
def Mid(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z
# R(M,W)
def Ref(X,Y):
    z=[2*X[0]-Y[0],2*X[1]-Y[1]]
    return z
#E(R,M)
def Exp(X,Y):
    z=[2*X[0]-Y[0],2*X[1]-Y[1]]
    return z

def fun(z):
    x=z[0]
    y=z[1]
    f= x**2-4*x+y**2-y-x*y
    return f
#C= Cont(W,M)
def Cont(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z
#S= Stre(W,B)
def Stre(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z




#E= Exp(R,M)
#C= Cont(W,M)
#S= Stre(W,B)
#M= Mid(B,G)
#R=Ref(M,W)



for i in range(0,8):
    Points=sorted([[B,fun(B)],[G,fun(G)],[W,fun(W)]],key=lambda x:x[1])
    B=Points[0][0]
    G=Points[1][0]
    W=Points[2][0]
    M= Mid(B,G)
    R=Ref(M,W)
    C= Cont(W,M)
    S= Stre(W,B)
    E= Exp(R,M)


    if fun(R) < fun(G):
        #Case I
        #print(" {:^20}   \t {:^20}   \t {:^20}".format(fun(B), fun(G), fun(W)))
        if fun(B) < fun(R):
            W=R


        else:
            if fun(E) < fun(B):
                W=E


            else:

                W=R


    if fun(R) < fun(W):
        W=R
        if fun(C) < fun(W):
            W=C
        else:
            W=S
            G=M



    print(Points)

Aucun commentaire:

Enregistrer un commentaire