Python 简单迭代法/Newton迭代法/弦截法 求方程的根

Python 简单迭代法/Newton迭代法/弦截法 求方程的根

模块导入

import math

直接上代码

"""
迭代方程为:e^x-x^2+3*x-2=0
构建函数方程 fun = math.exp(x)-x**2+3*x-2
方程导数  fun_dc = math.exp(x)-2*x+3
迭代初值 x = 0
"""
import math

"""简单迭代法"""
def easy_iteration(x):
    x_next = (x ** 2 - math.exp(x) + 2) / 3
    while abs(abs(x) - abs(x_next)) > 0.0001:
        x = x_next
        x_next = (x ** 2 - math.exp(x) + 2) / 3
    print(x, x_next)
    print('\n')


"""Newton迭代法"""
def Newton_iteration(x):
    fun = math.exp(x) - x ** 2 + 3 * x - 2
    fun_dc = math.exp(x) - 2 * x + 3
    x_next = x - fun / fun_dc
    while abs(abs(x) - abs(x_next)) > 0.0001:
        x = x_next
        fun = math.exp(x) - x ** 2 + 3 * x - 2
        fun_dc = math.exp(x) - 2 * x + 3
        x_next = x - fun / fun_dc
    print(x, x_next)
    print('\n')


"""弦截法"""
def string_iteration(x, x0):
    fun = math.exp(x) - x ** 2 + 3 * x - 2
    fun_x0 = math.exp(x0) - x0 ** 2 + 3 * x0 - 2
    x_next = x - fun * (x - x0) / (fun - fun_x0)
    while abs(abs(x) - abs(x_next)) > 0.0001:
        x = x_next
        fun = math.exp(x) - x ** 2 + 3 * x - 2
        x_next = x - fun * (x - x0) / (fun - fun_x0)
    print(x, x_next)
    print('\n')


if __name__ == '__main__':
    print('简单迭代法:')
    easy_iteration(x=0)

    print('Newton迭代法:')
    Newton_iteration(x=0)

    print('弦截法:')
    string_iteration(x=0, x0=0.25)

  • 4
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值