为什么我的答案的小数在Python中不正确?

2024-05-17 18:38:33 发布

您现在位置: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]和x10.0221的2范数

我试图找到我的代码中的错误所在,但发现它很困难…下面是我的代码

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))

Tags: and代码fromimportnumpy范数normnp
1条回答
网友
1楼 · 发布于 2024-05-17 18:38:33

你是如何计算真实值的

The question states that when b is inputted as b = [71; 42;-11;-37;-61; 52]T and N = 2, the answer that i am supposed to get is x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] and the norm of 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]]

就像你对待雅各比一样

希望这有帮助:)

相关问题 更多 >