Python数值分析实验 — 近似与求根

Python数值分析实验 — 近似与求根

可微近似

在这里插入图片描述
在这里插入图片描述
# problem 1
import math

def function(x):
    return math.pow(x, 3)

def method_1(i: int):
    x0 = 1
    h = math.pow(10, -i)
    return (function(x0+h)-function(x0))/h 

def method_2(i: int):
    x0 = 1
    h = math.pow(10, -i)
    return (function(x0+h)-function(x0-h))/(2*h)

if __name__ == "__main__":
    print("第一种方法       第二种方法")
    for i in range(16):
        print(str(method_1(i))+"     "+str(method_2(i)))

二分法和牛顿法求根

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

# problem 2
import math 
def function(x):
    return math.pow(x, 3) + math.pow(x, 2) - 3*x - 3

# 二分法
""" 
x0 初始值, sigma 容许误差 n 迭代上限
"""
x0 = 1.5
sigma = math.pow(10, -6)
n = 1000

def binary_split(x0, sigma, n):
    # (a, b)为求根区间上下界 count为迭代次数计数器
    a = math.floor(x0)
    b = math.ceil(x0)
    count = 0
    while (abs(b-a) > sigma and count < n):
        mid = (a+b)/2
        f1 , f2 , f3 = function(a) , function(mid) , function(b)
        if f1*f3 < 0 and f1*f2 < 0:
            b = mid 
            count+= 1
        else:
            a = mid 
            count+= 1
    if count < n:
        return (a+b)/2
    else:
        print("None")
        return 0

# 牛顿迭代法 使用单点弦法
def newton(x0, sigma, n):
    def func_diff(x1, x0):
        return (x1-x0)/(function(x1)-function(x0))
    # 迭代计数器 count
    count = 0
    x1 = math.ceil(x0)
    while abs(x1-x0) > sigma and count < n:
        x1 = x1 - func_diff(x0, x1)*(x1-x0)
        count += 1
    if count < n:
        return x1 
    else:
        print("None !")
        return 0
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值