函数是3x^2-2tan(x)
import math
import numpy as np
from matplotlib import pyplot as plt
def func(x):
return 3*x**2 -2*math.tan(x)
a = 0
b = 1
x1= a + 0.382 * (b - a)
funcx1 = func(x1)
x2= a + 0.618 * (b - a)
funcx2 = func(x2)
plt.scatter(0,3*0**2 -2*math.tan(0))
plt.scatter(1,3*1**2 -2*math.tan(1))
while (1):
if (funcx1 <= funcx2):
if (x2 - a <= 0.0001):
print("最优解:",x1)
print("最优值:",3*x1**2 -2*math.tan(x1))
print("终止条件为:(b-x1)<=0.0001")
plt.scatter(x1,3*x1**2 -2*math.tan(x1))
break
else:
b = x2
x2= x1
funcx2 = funcx1
x1 = a + 0.382 * (b - a)
funcx1 = func(x1)
print("x1=",x1)
print(3*x1**2 -2*math.tan(x1))
print("x2=",x2)
print("f(x2)=",3*x2**2 -2*math.tan(x2))
print("f((x1+x2)/2)=",3*((x1+x2)/2)**2 -2*math.tan(((x1+x2)/2)))
plt.scatter(x1,3*x1**2 -2*math.tan(x1))
plt.scatter(x2,3*x2**2 -2*math.tan(x2))
else:
if (b - x1 <= 0.0001):
print("最优解:",x2)
print("最优值:",3*x2**2 -2*math.tan(x2))
print("终止条件为:(b-x1)<=0.0001")
plt.scatter(x2,3*x2**2 -2*math.tan(x2))
break
else:
a = x1
x1 = x2
funcx1= funcx2
x2 = a + 0.618 * (b - a)
funcx2 = func(x1)
print("x1=",x1)
print(3*x1**2 -2*math.tan(x1))
print("x2=",x2)
print("f(x2)=",3*x2**2 -2*math.tan(x2))
print("f((x1+x2)/2)=",3*((x1+x2)/2)**2 -2*math.tan(((x1+x2)/2)))
plt.scatter(x1,3*x1**2 -2*math.tan(x1))
plt.scatter(x2,3*x2**2 -2*math.tan(x2))
x=np.arange(0,1,0.0001)
func=3*x**2-2*np.tan(x)
plt.xlabel('x')
plt.ylabel('func')
plt.plot(x,func)
plt.show()