脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现黄金分割法的示例代码

python实现黄金分割法的示例代码

2021-10-22 09:38jtwty Python

这篇文章主要介绍了python实现黄金分割法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一.问题

python实现黄金分割法的示例代码

使用黄金分割法来计算

二.代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#黄金分割法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-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)

三.结果

python实现黄金分割法的示例代码

到此这篇关于python实现黄金分割法的示例代码的文章就介绍到这了,更多相关python 黄金分割法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_46308081/article/details/116164984

延伸 · 阅读

精彩推荐