python中黄金分割法实现方法
本文实例讲述了python中黄金分割法实现方法。分享给大家供大家参考。具体实现方法如下:
'''a,b=bracket(f,xStart,h) Findsthebrackets(a,b)ofaminimumpointofthe user-suppliedscalarfunctionf(x). ThesearchstartsdownhillfromxStartwithastep lengthh. x,fMin=search(f,a,b,tol=1.0e-6) Goldensectionmethodfordeterminingxthatminimizes theuser-suppliedscalarfunctionf(x). Theminimummustbebracketedin(a,b). ''' frommathimportlog,ceil defbracket(f,x1,h): c=1.618033989 f1=f(x1) x2=x1+h;f2=f(x2) #Determinedownhilldirectionandchangesignofhifneeded iff2>f1: h=-h x2=x1+h;f2=f(x2) #Checkifminimumbetweenx1-handx1+h iff2>f1:returnx2,x1-h #Searchloop foriinrange(100): h=c*h x3=x2+h;f3=f(x3) iff3>f2:returnx1,x3 x1=x2;x2=x3 f1=f2;f2=f3 print"Bracketdidnotfindamimimum" defsearch(f,a,b,tol=1.0e-9): nIter=int(ceil(-2.078087*log(tol/abs(b-a))))#Eq.(10.4) R=0.618033989 C=1.0-R #Firsttelescoping x1=R*a+C*b;x2=C*a+R*b f1=f(x1);f2=f(x2) #Mainloop foriinrange(nIter): iff1>f2: a=x1 x1=x2;f1=f2 x2=C*a+R*b;f2=f(x2) else: b=x2 x2=x1;f2=f1 x1=R*a+C*b;f1=f(x1) iff1<f2:returnx1,f1 else:returnx2,f2
希望本文所述对大家的Python程序设计有所帮助。
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短