"""
迭代方程为: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
"""简单迭代法"""defeasy_iteration(x):
x_next =(x **2- math.exp(x)+2)/3whileabs(abs(x)-abs(x_next))>0.0001:
x = x_next
x_next =(x **2- math.exp(x)+2)/3print(x, x_next)print('\n')"""Newton迭代法"""defNewton_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
whileabs(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')"""弦截法"""defstring_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)whileabs(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)