首页 > 解决方案 > 为什么我的答案在 Python 中的小数点不正确?

问题描述

我目前正忙于一个问题,需要使用 Jacobi 方法解决 Ax = b,其中创建的函数必须返回 x 和 x 的 2 范数。

问题指出,当 b 输入为

b = [71; 42;-11;-37;-61; 52]
T = 2
N = 2

我应该得到的答案是x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821]x 的范数10.0953

但是我得到x = [ 3.07507642; 0.58675203; -0.64849988; 5.33343053; 6.66765397; 4.16161712]了 x 的 2 范数10.0221

我试图找出我的代码中的错误在哪里,但发现它很困难......下面是我的代码

import numpy as np
from numpy.linalg import norm
from numpy import array
from scipy.linalg import solve


def jacobi(A, b, x0, N):

    n = A.shape[0]
    x = x0.copy()
    k = 0
    x_prev= x0.copy()

    for i in range(0, n):
        subs = 0.0
        for j in range(0, n):
            if i != j:
                subs += np.matrix(A[i,j])*np.matrix(x_prev[j])

        x[i] = (b[i]-subs)/np.matrix(A[i,i])

    k += 1

    return(x)


A = array([[18, 1, 4, 3, -1, 2],
           [2, 12, -1, 7, -2, 1],
           [-1, 1, -9, 2, -5, 2],
           [2, 4, 1, -12, 1, 3],
           [1, 3, 1, 7, -16, 1],
           [-2, 1, 7, -1, 2, 13]]) 

x0 = array([[0],[0],[0],[0],[0],[0]])

elements_of_b_and_N = list(map(float, input().split(' ')))
b_and_N = array(elements_of_b_and_N).reshape(A.shape[0]+1, )
b = b_and_N[:A.shape[0]]
N = b_and_N[A.shape[0]]

x = jacobi(A, b, x0, N)
print((solve(A, b)))
print(round(norm((solve(A,b)), 2), 4))

标签: pythonarraysnumpyscipy

解决方案


你是如何计算真实值的?

问题指出,当 b 输入为 b = [71; 42;-11;-37;-61; 52]T 和 N = 2,我应该得到的答案是 x = [2.73186728; 1.44791667;0.62885802;6.32696759;6.390625;3.33012821] 和 x 的范数 10.0953

当我执行:

x0 = array([[0], [0], [0], [0], [0], [0]], dtype=float)
A = array([[18, 1, 4, 3, -1, 2],
       [2, 12, -1, 7, -2, 1],
       [-1, 1, -9, 2, -5, 2],
       [2, 4, 1, -12, 1, 3],
       [1, 3, 1, 7, -16, 1],
       [-2, 1, 7, -1, 2, 13]])
b = array([[71], [42], [-11], [-37], [-61], [52]], dtype=float)

print(solve(A, b))

我得到:

[[ 3.07507642]
[ 0.58675203]
[-0.64849988]
[ 5.33343053]
[ 6.66765397]
[ 4.16161712]]

正如你对雅各比所做的那样。

希望这可以帮助 :)


推荐阅读