python實(shí)現(xiàn)黃金分割法的示例代碼
使用黃金分割法來計(jì)算
二.代碼#黃金分割法python求解PPT上第一個(gè)例題#因?yàn)楹瘮?shù)要求解最大值而這個(gè)方法一般求解最小值所以把函數(shù)取負(fù)import numpy as npimport matplotlib.pyplot as pltrate = 0.618034def f(x): #求解體積函數(shù)公式,乘1.0將結(jié)果變?yōu)楦↑c(diǎn)數(shù) return -1.0*x*(350-2*x)*(260-2*x) def tarceback(f,a0,b0,accuracy): a = a0 b = b0 x2 = a+rate*(b-a) x1 = b-rate*(b-a) f1 = f(x1) f2 = f(x2) print(x1,x2) arr = search(f,a,b,x1,x2,f1,f2,accuracy) printFunc(f,a,b,arr[0],arr[1]) def search(f,a,b,x1,x2,f1,f2,accuracy): if f1<=f2:if x2-a<accuracy: print(x1,f1) return (x1,f1)else: b = x2 x2 = x1 f2 = f1 x1 = a+b-x2 f1 = f(x1) print(x1,x2) return search(f,a,b,x1,x2,f1,f2,accuracy) else:if b-x1<accuracy: print(x2,f2) return (x2,f2)else: a = x1 x1 = x2 f1 = f2 x2 = a+b-x1 f2 = f(x2) print(x1,x2) return search(f,a,b,x1,x2,f1,f2,accuracy)def printFunc(f,a,b,x,y): t = np.arange(a,b,0.01) s = f(t) plt.plot(t,s) plt.plot([x],[y],’ro’) plt.plot([x,x],[y,0],’k--’) plt.plot([0,x],[y,y],’k--’)# plt.annotate(r’$(x,y)$’,xy=(x,y)) plt.show()tarceback(f,0,130,0.05)三.結(jié)果
到此這篇關(guān)于python實(shí)現(xiàn)黃金分割法的示例代碼的文章就介紹到這了,更多相關(guān)python 黃金分割法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. PHP字符串前后字符或空格刪除方法介紹4. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法5. nestjs實(shí)現(xiàn)圖形校驗(yàn)和單點(diǎn)登錄的示例代碼6. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程7. XML入門的常見問題(一)8. jsp cookie+session實(shí)現(xiàn)簡易自動(dòng)登錄9. css進(jìn)階學(xué)習(xí) 選擇符10. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖
