"""
求解线性方程组
5*x_1 - x_2 + x_3 = 10
2*x_1 - 8*x_2 - x_3 = 11
-x_1 + x_2 + 4*x_3 = 3
初值为 x1 = x2 = x3 = 0
"""
"""雅可比迭代法"""
def jacobi_iteration():
x1 = x2 = x3 = 0
x1_next = (x2 - x3 + 10) / 5
x2_next = (-2 * x1 + x3 + 11) / 8
x3_next = (x1 - x2 + 3) / 4
while abs(abs(x1) - abs(x1_next)) > 0.0001 or abs(abs(x2) - abs(x2_next)) > 0.0001 or abs(
abs(x3) - abs(x3_next)) > 0.0001:
x1 = x1_next
x2 = x2_next
x3 = x3_next
x1_next = (x2 - x3 + 10) / 5
x2_next = (-2 * x1 + x3 + 11) / 8
x3_next = (x1 - x2 + 3) / 4
print('x1:\n {0} {1}'.format(x1, x1_next))
print('x2:\n {0} {1}'.format(x2, x2_next))
print('x3:\n {0} {1}\n'.format(x3, x3_next))
"""高斯-赛德尔迭代法"""
def Gauss_Seidel_iteration():
x1 = x2 = x3 = 0
x1_next = (x2 - x3 + 10) / 5
x2_next = (-2 * x1_next + x3 + 11) / 8
x3_next = (x1_next - x2_next + 3) / 4
while abs(abs(x1) - abs(x1_next)) > 0.0001 or abs(abs(x2) - abs(x2_next)) > 0.0001 or abs(
abs(x3) - abs(x3_next)) > 0.0001:
x1 = x1_next
x2 = x2_next
x3 = x3_next
x1_next = (x2 - x3 + 10) / 5
x2_next = (-2 * x1_next + x3 + 11) / 8
x3_next = (x1_next - x2_next + 3) / 4
print('x1:\n {0} {1}'.format(x1, x1_next))
print('x2:\n {0} {1}'.format(x2, x2_next))
print('x3:\n {0} {1}\n'.format(x3, x3_next))
if __name__ == '__main__':
print('雅可比迭代法:')
jacobi_iteration()
print('高斯-赛德尔迭代法')
Gauss_Seidel_iteration()
雅可比迭代、高斯-赛德尔迭代
于 2022-03-06 16:37:46 首次发布