#Python dry goods #python implementation -- optimization algorithm

Posted by mmosel on Tue, 21 Dec 2021 09:59:35 +0100

dichotomy

The function is shown in rres. This code makes the algorithm run twice

def asdf(x):
    rres=8*x**3-2*x**2-7*x+3
    return rres

i=2
left=0
right=1
while i>0 :
    i = i-1
    ans = 0.1
    mid1 = (left + right + ans) / 2
    mid2 = (left + right - ans) / 2
    a=asdf(mid1)
    c=asdf(mid2)
    if a > c :
        right = mid1
    else :
        left = mid2
b=(left+right) / 2
print("Left limit=%s,Right limit=%s,Minimum x=%s"%(left,right,b))
Left limit=0.45,Right limit=0.775,Minimum x=0.6125

harvest:
This is my first implementation code. After learning the algorithm, the logical framework basically exists, and the rest that needs to be clarified is the corresponding python language. So I started looking for the formats of "how to define a function" (see Youku of mofan for details), "loop body" and "if conditional statement"( https://blog.csdn.net/qq\_39407518/article/details/79822498 )"Mathematical symbols" (see Youku of mofan for details) and the use of print

1.def refers to the definition in python. It is generally used to define functions. If you need deep learning to build a network, it can be used to define the network. It is worth noting that

return must be added to another line after the function.

I don't know why, but if it's not added, the function formula is a vase, just like a result can't be output.

2. The most pitiful thing is logic. At first, the logic was not clear, or there were omissions in the code, which led me to put left and right in the loop body. The result can be imagined. But also because of this error, I know how to use debug in pycharm. It's very simple. Baidu comes out at once.

3. I don't know why. Don't bother watching the print in the video. There is no way to output multiple variables together in my pycharm. The results are very strange. Maybe it's because I'm win10, not ios. Print if multiple variables are output together, it must be print("Name:% s, name 2:% s"%(a,b)). The result output is name: A, name 2: B

Question: 1 Why add return?

return means to output the value of any variable in this def as the result. Generally speaking, it is the naming of the relational expression of the output function, so that when you call this function, the function value corresponding to the variable can be displayed. Otherwise, it will only run without results and will not have effect.

Grid method -- three-point bisection method

import numpy as np
def qwer(x):
    third = np.exp(x) - 5*x
    return third

left = 1
right = 2
mid1 =float(left+right) / 2
mid2 = (left+mid1) / 2
mid3 = (mid1+right) /2
a = qwer(mid1)
b = qwer(mid2)
c = qwer(mid3)
i = 5
while i > 0:
    i=i-1
    if a > b:
        if c > b :
            #b
            right = mid1
            mid1 = mid2
            a=b
            mid2 = (left + mid1) / 2
            mid3 = (mid1 + right) / 2
            b = qwer(mid2)
            c = qwer(mid3)
        else:#b>c
            #c
            left = mid1
            mid1 = mid3
            a = c
            mid2 = (left + mid1) / 2
            mid3 = (mid1 + right) / 2
            b = qwer(mid2)
            c = qwer(mid3)
    else:#b>a
            if a > c:
                #C
                left = mid1
                mid1 = mid3
                a = c
                mid2 = (left + mid1) / 2
                mid3 = (mid1 + right) / 2
                b = qwer(mid2)
                c = qwer(mid3)
            else:#b>a&c>a
                # a
                left = mid2
                right = mid3
                mid2 = (left + mid1) / 2
                mid3 = (mid1 + right) / 2
                b = qwer(mid2)
                c = qwer(mid3)

print("minimum value=%s"%mid1)
print("function value=%s"%a)
minimum value=1.609375
 function value=-3.047189552275773

About data variables in python. The result of the first run was obviously wrong, so I used debug. It was found that mid1 was always 1 instead of 1.5, so we began to understand the data variables. At first, I guessed that all variables in python are integers by default, but according to the result of dichotomy, I realized that this guess was wrong, so it is not necessary to change the variable format of the whole file. So I added a float in front of mid1 formula, and the result is 1.5. But if I use the whole formula () is enclosed, followed by float, and the result is still 1. I don't quite understand why. However, I know that the data format of python is determined by the input quantity, that is, if your input quantity is an integer, the calculation output directly related to it must be an integer, and the carry integer is not used. Before I did not use + float/+.0, mid 1 ~ 3 are all integers.

left = 1.0
right = 2.0
mid1 =(left+right) / 2

Or instead of adding float in front of mid1, just click a point after the input quantity
Really want to Tucao print, make complaints about ah, ah, every time I have to get a%s, and sometimes can not put together!!!!

Fibonacci method

def fibonacci(n):
    i=0
    a = 0
    b = 1
    for i in range(n):
        i=i+1
        c = a+b
        a = b
        b = c
    return c
def bn(x):
    ert = x**2 - 6*x + 2
    return ert
z = 2
p = 0
left = 0.00000
right = 10.00000
L1 = right - left
while z < 100:
    m = fibonacci(z)
    l = L1/m
    k = 1.000/m
    if k < 0.03:
        print("n=%s,Fn=%s"%(z,m))
        L2 = l*fibonacci(z-1)
        t = left + L2
        r = right -L2
        while p < 3:
            p = p + 1
            l3 = t - r
            e= bn(t)
            o = bn(r)
            if e>o :
                right = t
                t = r
                r = left + l3
            else:#o>e
                left = r
                r = t
                t = right - l3
        break
    else:
        z = z + 1

okk=(left+right)/2
okky=bn(okk)
print(left)
print(right)
print("Minimum x=",okk)
print("Minimum y=",okky)

Don't ask me what I have mastered, ask me how much I love the precision of python after writing this Code: -) I decided to fill a lot of zeros after the small mathematical points of input as long as I write the code of mathematical formula in the future
fibonacci function definition: after each debug, my hand is shaking O(∩ \ ∩) O~

Golden section method

def gold(x):
    gg= x**2 - 6*x + 9
    return gg

left = 1
right = 7
ans = 0.4
a = left + 0.618 * (right - left)
b = left + 0.382*(right - left)
gga = gold(a)
ggb = gold(b)
i = 0
while i < 7:
    print("i=%s" % i)
    print("left=%s,right=%s" % (left, right))
    print("x Left=%s,x right=%s" % (a, b))
    print("y Left=%s,y right=%s" % (ggb, gga))
    c = right - left
    if c > 0.4:
        i = i + 1
        if gga > ggb:
            right = a
            a = b
            b = left + 0.382*(right - left)
            gga = ggb
            ggb = gold(b)
        else:#gga<ggb
            left = b
            b = a
            a = left + 0.618 * (right - left)
            ggb = gga
            gga = gold(a)
    else:
        break

I don't know when I have OCD. As long as there is "~" under the code, I must eliminate it. Laugh and cry. This is very simple. The first four are very simple except Fibonacci.

Indirect method -- quadratic interpolation method

def yy(x):
    y=x**4-4*x**3-6*x**2-16*x+4
    return y

def xing(xm1,xm2,xm3,fm1,fm2,fm3):
    yxxx=0.5000*((xm2**2-xm3**2)*fm1+(xm3**2-xm1**2)*fm2+(xm1**2-xm2**2)*fm3)/((xm2-xm3)*fm1+(xm3-xm1)*fm2+(xm1-xm2)*fm3)
    return yxxx

x1 = -1.0000
f1 = yy(x1)
x3 = 6
f3 = yy(x3)
x2 = 0.50000*(x1+x3)
f2 = yy(x2)
xp = xing(x1,x2,x3,f1,f2,f3)
fp = yy(xp)
a = abs(xp-x2)
while abs(xp-x2) > 0.05000:
    a = abs(xp - x2)
    if xp > x2:
        if fp > f2:
            x3=xp
            f3=fp
            xp = xing(x1, x2, x3, f1, f2, f3)
            fp = yy(xp)
            print("ans=%s" % a)
            print("left=%s,right=%s" % (x1, x3))
            print("x*=%s,fp*=%s" % (xp, fp))
            print("x2=%s,f2=%s" % (x2, f2))
            print("******************")
        else:#f2>fp
            x1 = x2
            f1 = f2
            x2 = xp
            f2 = fp
            xp = xing(x1, x2, x3, f1, f2, f3)
            fp = yy(xp)
            print("ans=%s" % a)
            print("left=%s,right=%s" % (x1, x3))
            print("x*=%s,fp*=%s" % (xp, fp))
            print("x2=%s,f2=%s" % (x2, f2))
            print("******************")
    else:#xp<x2
        if fp > f2:
            x1 = xp
            f1 = fp
            xp = xing(x1, x2, x3, f1, f2, f3)
            fp = yy(xp)
            print("ans=%s" % a)
            print("left=%s,right=%s" % (x1, x3))
            print("x*=%s,fp*=%s" % (xp, fp))
            print("x2=%s,f2=%s" % (x2, f2))
            print("******************")
        else:
            x3 = x2
            f3 = f2
            x2 = xp
            f2 = fp
            xp = xing(x1, x2, x3, f1, f2, f3)
            fp = yy(xp)
            print("ans=%s" % a)
            print("left=%s,right=%s" % (x1, x3))
            print("x*=%s,fp*=%s" % (xp, fp))
            print("x2=%s,f2=%s" % (x2, f2))
            print("******************")

This formula looks very troublesome, so you should be more careful when writing it. I put that 2 under the semicolon last time, and the result is very big, so it's better to convert it to 0.5 (PS: don't forget the long river of 0).
Although the code is very long, it is mainly because there are too many prints. It was intended to print at the beginning, but the last part will be omitted in the final result. I'm too lazy to think of other ways. Let's just do it

Indirect method Newton method

def fd(x):
    y = 4*x**3-12*x**2-12*x-16
    return y
def fdd(x):
    ys = 12*x**2-24*x-12
    return ys

i = 1
x0 = 3.00000
ans = 0.001
while i < 7:
    fd0 = fd(x0)
    fdd0 = fdd(x0)
    if abs(fd0) > ans:
        x1 = x0 - (fd0/fdd0)
        x0 = x1
        print("Times:%s,Value obtained x:%s"%(i,x1))
        i = i + 1
    else:#fd0<0.001
        print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
        print("Bingo!Smooth customs clearance! I wish you a happy start to school!")
        print("Boss  X=%s"%x0)
        break

At first, the < in while was written >, resulting in the failure of run. Then, debug doesn't work. After checking on the Internet, you know "no networking" + "no breakpoint selected". Finally, I tried to output the content in else, but I found that run was swiped later. So after I < 7, I still couldn't do it, so I wanted to add a break to jump out of the loop, and the result was effective.
After debug ging, I realized that i+1 was in if. Because there was no way to + 1, i=6 always existed and kept cycling. Because you can add break or i+1.

Just an hour and a half ago, I successfully completed the six optimization codes, pure hand, no external force. happy!

This is my first group of python code implemented by myself, that is, mathematical formulas are assembled in python language. At the beginning, I know what needs to be reflected in the language, but I'm not very clear. So I found several dichotomy on the Internet. They are different, but the framework is the same. However, if we want to use our formula, we still need to change a lot. Then I began to analyze our problem. I found that it generally needs two parts, one is function definition, and the other is loop body. But I don't know how to define functions, how to write mathematical formulas, how to get variables, that is, some small points are not very good, so I choose Baidu directly. Because I know my reading ability is good. I'm better at getting key points through reading than extracting elements from videos. Find knowledge points purposefully and master them more firmly.
So I began to write the first dichotomy. I found that I made a lot of mistakes, and many places were very basic. But I still didn't choose the video, but directly find these problems on Baidu, because maybe you didn't find something after the video. Of course, this is a step-by-step process, not directly put the program up and change it bit by bit.
With the success of the first two, I found that I had confidence in these codes, seemed to see through their disguise and grasped the essence. In addition, I also realize that my learning ability seems to have improved a lot since August, and I have more effective learning methods. There has been a certain awakening in all aspects. In addition to the first to find a few wrong codes, others are written according to their own logic. After the logic is passed, a part of the corresponding language does not know how to translate and goes to Baidu. In fact, these routines are the same, or the routines of mathematical formula transformation are the same.
I also realized that assembly is actually the most difficult language. What I have learned so far is that many of them need to be defined by themselves. They need to remember a large number of instructions and can't be flexible. But others just need to write down some corresponding ones. Python is really simple. Moreover, I found that today I seem to have opened the door to the new world. I fell in love with this spiritual thing, full of rigorous beauty, and the unknown changes. I found that I seem to fall in love with code. Perhaps not just python, these languages are full of challenges. I think when you doubt, you need to trust your intuition. At least I find it accurate

last

If the article is helpful to you, like + pay attention, your support is my biggest motivation

Topics: Python