用PYTHON实现黄金分割法

  • 格式:pdf
  • 大小:55.45 KB
  • 文档页数:4

下载文档原格式

  / 4
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用Python实现黄金分割法

"""

Author:Z

Date:2015-12-3

"""

import os,sys,time

import numpy as np

class node(object):

def__init__(self):

self.power=[]

self.a=[]

self.left=0.0

self.right=1.0

##############################base function area################ def parse(self,string):

"""

parse str"string"into list"a"and"power"

"a"means the factor of x

"power"means the index of x

"""

self.power=[]

self.a=[]

string=string.replace('','')

eq=string.find('=')

new_string=string[(eq+1):]

index=new_string.find('x')

while(index!=-1):

if new_string[index-1]=='*'and new_string[index-2].isdigit():

i=index-2

num=""

while i>=0and new_string[i].isdigit():

num=new_string[i]+num

i=i-1

if i>=0and new_string[i]=='-':

num='-'+num

self.a.append(float(num))

else:

self.a.append(1.)

if new_string[index+1]=='^':

num=0.

i=index+2

while i

num=10*num+float(new_string[i])

i=i+1

self.power.append(num)

else:

self.power.append(1.)

index=new_string.find('x',index+1)

if new_string[-1]!='x':

ll=len(new_string)-1

num=""

while ll>=0and new_string[ll].isdigit():

num=new_string[ll]+num

ll=ll-1

if ll>=0and new_string[ll]=='-':

num='-'+num

self.a.append(float(num))

self.power.append(0.)

def getinterval(self,interval):

self.left=np.array(interval)[0]

self.right=np.array(interval)[1]

def get_fun_value(self,num):

ret=0.

for i in xrange(np.array(self.a).shape[0]):

ret+=self.a[i]*pow(num,self.power[i])

return ret

######################tool function area######################### def findMin(self,max_epoch,error_index):

lef=self.left

rig=self.right

epoch=0

while True:

mid2=lef+0.618*(rig-lef)

mid1=lef+0.382*(rig-lef)

y1=self.get_fun_value(mid1)

y2=self.get_fun_value(mid2)

if y1

lef=lef

rig=mid2

else:

lef=mid1

rig=rig

epoch+=1

if epoch>=max_epoch or(rig-lef)/(self.right-self.left)<=error_index: break

x=(lef+rig)/2.

y=self.get_fun_value(x)

return x,y

def findMax(self,max_epoch,error_index):

lef=self.left

rig=self.right

while True:

mid1=lef+0.382*(rig-lef)

mid2=lef+0.618*(rig-lef)

if self.get_fun_value(mid2)>self.get_fun_value(mid1):

lef=mid1

rig=rig

else:

rig=mid2

lef=lef

epoch+=1

if epoch>=max_epoch or(rig-lef)/(self.right-self.left)<=error_index: break

x=(lef+rig)/2,

y=self.get_fun_value(x)

return x,y

###############################show area#################### def printf(self):

print'a[]is:',

for i in xrange(np.array(self.a).shape[0]):

print self.a[i],

print''

print'power[]is:',

for i in xrange(np.array(self.power).shape[0]):

print self.power[i],

print''