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