#黄金分割法python求解PPT上第一个例题
#因为函数要求解最大值而这个方法一般求解最小值所以把函数取负
import numpy as np
import matplotlib.pyplot as plt
rate = 0.618034
def f(x):
#求解体积函数公式,乘1.0将结果变为浮点数
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-aaccuracy:
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-x1accuracy:
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)
到此这篇关于python实现黄金分割法的示例代码的文章就介绍到这了,更多相关python 黄金分割法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!