黄金分割

class hyj_gold():
    def __init__(self):
        self.X = np.linspace(-2, 2, 100)
        self.Y = [f(x) for x in X]

    def f(self,x):
        return x*x-x-1
    
    def goldOpt(self,a, b, theta):
        alpha = (math.sqrt(5) - 1) / 2
        t1 = a + (1 - alpha)*(b - a)
        t2 = a + alpha*(b - a)
        step_num = 0
        while abs(b-a) > theta:
            step_num += 1
            f1 = self.f(t1)
            f2 = self.f(t2)
            if f1 < f2:
                b = t2
                t2 = t1
                f2 = f1
                t1 = a + (1 - alpha)*(b - a)
            else:
                a = t1
                t1 = t2
                f1 = f2
                t2 = a + alpha * (b - a)
                x_opt = (a + b) / 2
                y_opt = f(x_opt)
        print("Finished")
        print('(%.2f,%.2f) is the optimal point and iterate %d times' % (x_opt, y_opt, step_num))
        return (x_opt, y_opt, step_num)
        
    def plt(self):
        x_opt, y_opt, step_num = self.goldOpt(a=0, b=1, theta=10**-5)
        fig = plt.figure()
        ax = axisartist.Subplot(fig, 111)
        fig.add_axes(ax)
        ax.axis["bottom"].set_axisline_style("-|>", size=1.5)
        ax.axis["left"].set_axisline_style("->", size=1.5)
        ax.axis["top"].set_visible(False)
        ax.axis["right"].set_visible(False)
        plt.title(r'$Golden \ section$')
        plt.plot(self.X, self.Y)
        plt.plot(x_opt, y_opt, 'r*')
        plt.xlabel(r'$x$', fontsize=20)
        plt.ylabel(r'$y$', fontsize=20)
        plt.show()
hyj = hyj_gold()
hyj.plt()

黄金分割_第1张图片

你可能感兴趣的:(优化,python,numpy,机器学习)