解非线性方程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
相关推荐
科雷软件测试1 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO2 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
别或许4 小时前
1、高数----函数极限与连续(知识总结)
算法
派大星~课堂4 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
田梓燊4 小时前
code 560
数据结构·算法·哈希算法
Thomas.Sir4 小时前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
笨笨饿4 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu4 小时前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
weixin_413063215 小时前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
ZTL-NPU5 小时前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion