0.618法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tlzhatao/article/details/72652082

一、简介

0.618法又称黄金分割法,是优选法的一种。是在优选时把尝试点放在黄金分割点上来寻找最优选择。0.618法是根据黄金分割原理设计的,所以又称之为黄金分割法。优选法是一种求最优化问题的方法。

二、实现

# -*- coding: utf-8 -*-
"""
Created on Tue May 23 13:10:17 2017

    0.618法    

@author: Administrator
"""

import numpy as np
import matplotlib.pyplot as plt

epsilon = 1e-3
alpha = 0.618
# -2 - 3
def f(x):
    return np.e**(-x) + x**2

def solve(a,b):
    count = 0
    while b - a > 0:
        lam = a + (1 - alpha) * (b - a)
        mu = a + alpha * (b - a)
        print 'count: %d' % count
        print 'a: %f' % a
        print 'b: %f' % b
        print 'b-a: %f' % (b-a)
        print 'lambda: %f' % lam
        print 'mu: %f' % mu
        print '---------------------'
        if b - a < epsilon:
            return (a + b) / 2,f((a + b) / 2)
        elif f(lam) > f(mu):
            a = lam
            lam = mu
            mu = a + alpha * (b - a)
        elif f(lam) <= f(mu):
            b = mu
            mu = lam
            lam = a + (1 - alpha) * (b - a)
        count += 1

def draw(ans):
    x = np.linspace(-2,3,1000)
    y = f(x)
    fig = plt.figure(figsize=(8,4))
    ax = fig.add_subplot(111)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.plot(x,y,color='r',linestyle='-.',label='f(x)')
    ax.scatter(ans[0],ans[1])
    ax.legend(loc='upper right')
    fig.show()
    fig.savefig('a.png')

def main():
    ans = solve(-2.0,3.0)
    draw(ans)
    print ans

if __name__ == '__main__':
    main()

0.618法

猜你喜欢

转载自blog.csdn.net/tlzhatao/article/details/72652082