雅可比迭代、高斯-赛德尔迭代

"""
求解线性方程组
    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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值