解非线性方程python实现黄金分割法

1.基本概念

黄金分割法(Golden Section Method)也叫0.618法,也是一种在区间上进行迭代的数值计算方法。它与二分法都通过不断缩小搜索区间来逼近方程的解。与二分法不同的是,二分法将搜索区间均匀地切割为两半,而黄金分割法将搜索区间不等分为两部分,每次迭代后搜索区间按照黄金分割比例缩小。

2.代码实现

下面简单实现方程 f(x)=x^3-x-1=0在1到1.5之间的根。要求用四位小数计算,精确到10-2

python 复制代码
"""
@Time : 2023/11/12 0012 15:57
@Auth : yeqc
"""

# 初始区间
left = 1
right = 1.5
N = 1000  # 最大迭代次数
# 黄金分割比例
golden_ratio = (5 ** 0.5 - 1) / 2
epsilo = 10 ** (-10)


def function(x):
    return x ** 3 - x - 1


for i in range(0, N):
    center = left + (right - left) * golden_ratio
    f_left = function(left)
    f_right = function(right)
    f_center = function(center)

    if f_left * f_center < 0:
        right = center
    elif f_center * f_right < 0:
        left = center
    print(f"结果: i = {i}, x = {center}, y = {function(center)}")
    # 区间小于10-2或者函数值小于10-2 跳出循环
    if (right - left) < epsilo or abs(f_center) < epsilo:
        break
相关推荐
JHC0000002 小时前
基于Ollama,Milvus构建的建议知识检索系统
人工智能·python·milvus
mOok ONSC2 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
Darkwanderor2 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo2 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣2 小时前
力扣热门100题之环形链表
算法·leetcode·链表
GIS兵墩墩3 小时前
postgis--PostgreSQL16及其plpython3u扩展
python·postgis
new Object ~3 小时前
LangChain的短期记忆存储实现
python·langchain
魔都吴所谓3 小时前
【Python】从零构建:IP地理位置查询实战指南
开发语言·python·tcp/ip
py有趣3 小时前
力扣热门100题之回文链表
算法·leetcode·链表