Python黄金分割法求极值加画图

函数是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()

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值