45 lines
921 B
Python
45 lines
921 B
Python
def fd1(x):
|
|
return 1+1/x**2
|
|
|
|
def fd2(x):
|
|
return 1/(x-1)**0.5
|
|
|
|
# 迭代法求解方程
|
|
def Renew(x,fd,err):
|
|
count=0
|
|
i = 0
|
|
try:
|
|
while True:
|
|
xk = fd(x)
|
|
if abs(i) < (xk-x):
|
|
count += 1
|
|
else:
|
|
count = 0
|
|
if count > 10:
|
|
print("不收敛")
|
|
break
|
|
if abs(xk-x) < err:
|
|
return xk
|
|
i = xk-x
|
|
x = xk
|
|
except Exception as e:
|
|
print(f"发生错误: {e}")
|
|
return None
|
|
return None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
x0 = 1.5
|
|
|
|
result = Renew(x0, fd1, 1e-5)
|
|
if result is not None:
|
|
print(f"1式收敛 解为: {result:.5f}")
|
|
else:
|
|
print("1式不收敛")
|
|
|
|
result = Renew(x0, fd2, 1e-5)
|
|
if result is not None:
|
|
print(f"2式收敛 解为: {result:.5f}")
|
|
else:
|
|
print("2式不收敛")
|