python中黄金分割法实现方法

作者:songguo 时间:2022-05-15 01:45:24 

本文实例讲述了python中黄金分割法实现方法。分享给大家供大家参考。具体实现方法如下:


''' a,b = bracket(f,xStart,h)
 Finds the brackets (a,b) of a minimum point of the
 user-supplied scalar function f(x).
 The search starts downhill from xStart with a step
 length h.
 x,fMin = search(f,a,b,tol=1.0e-6)
 Golden section method for determining x that minimizes
 the user-supplied scalar function f(x).
 The minimum must be bracketed in (a,b).
'''    
from math import log, ceil
def bracket(f,x1,h):
 c = 1.618033989
 f1 = f(x1)
 x2 = x1 + h; f2 = f(x2)
# Determine downhill direction and change sign of h if needed
 if f2 > f1:
   h = -h
   x2 = x1 + h; f2 = f(x2)
  # Check if minimum between x1 - h and x1 + h
   if f2 > f1: return x2,x1 - h
# Search loop
 for i in range (100):  
   h = c*h
   x3 = x2 + h; f3 = f(x3)
   if f3 > f2: return x1,x3
   x1 = x2; x2 = x3
   f1 = f2; f2 = f3
 print "Bracket did not find a mimimum"    
def search(f,a,b,tol=1.0e-9):
 nIter = int(ceil(-2.078087*log(tol/abs(b-a)))) # Eq. (10.4)
 R = 0.618033989
 C = 1.0 - R
# First telescoping
 x1 = R*a + C*b; x2 = C*a + R*b
 f1 = f(x1); f2 = f(x2)
# Main loop
 for i in range(nIter):
   if f1 > f2:
     a = x1
     x1 = x2; f1 = f2
     x2 = C*a + R*b; f2 = f(x2)
   else:
     b = x2
     x2 = x1; f2 = f1
     x1 = R*a + C*b; f1 = f(x1)
 if f1 < f2: return x1,f1
 else: return x2,f2

希望本文所述对大家的Python程序设计有所帮助。

标签:python,黄金分割法
0
投稿

猜你喜欢

  • IE9初窥:支持CSS3,和HTML5?

    2009-12-01 14:20:00
  • 自动化收集SQLSERVER诊断信息的工具选择及使用介绍

    2024-01-14 11:01:04
  • SQL Server误区30日谈 第28天 有关大容量事务日志恢复模式的误区

    2024-01-19 23:08:55
  • MySQL 通过索引优化含ORDER BY的语句

    2024-01-12 19:16:06
  • 在SQL Server中使用CLR调用.NET方法

    2008-12-24 15:43:00
  • Sqlserver 常用日期时间函数

    2024-01-16 04:35:44
  • 使用Python和xlwt向Excel文件中写入中文的实例

    2023-08-27 19:18:08
  • Scrapy+Selenium自动获取cookie爬取网易云音乐个人喜爱歌单

    2023-06-26 10:15:54
  • 使用JS+XML(数据岛)实现分页)

    2005-08-18 00:46:06
  • Python列表切片操作实例总结

    2023-01-30 16:06:57
  • css+js实现部分区域高亮可编辑遮罩层

    2024-02-25 08:49:23
  • MySQL load语句详细介绍

    2024-01-27 01:31:05
  • python获取Pandas列名的几种方法

    2022-10-31 09:29:27
  • Javascript 获取css属性

    2009-05-31 16:49:00
  • MySQL远程访问设置终极方法

    2024-01-19 02:31:43
  • Python时间戳与时间字符串互相转换实例代码

    2022-09-04 23:39:25
  • Django中对数据查询结果进行排序的方法

    2021-01-31 23:40:18
  • python中split(), os.path.split()和os.path.splitext()的用法

    2022-03-23 09:06:40
  • Python中更优雅的日志记录方案详解

    2023-09-02 13:43:03
  • mysql installer web community 5.7.21.0.msi安装图文教程

    2024-01-25 02:35:23
  • asp之家 网络编程 m.aspxhome.com