简体   繁体   中英

Why are my answer's decimals incorrect in Python?

I am currently busy with a question that requires for one to solve Ax = b using Jacobi method where the function created must return x and the 2 norm of x.

The question states that when b is inputted as

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

The answer that i am supposed to get is x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] x = [2.73186728; 1.44791667; 0.62885802; 6.32696759; 6.390625; 3.33012821] and the norm of x 10.0953

However I get x = [ 3.07507642; 0.58675203; -0.64849988; 5.33343053; 6.66765397; 4.16161712] x = [ 3.07507642; 0.58675203; -0.64849988; 5.33343053; 6.66765397; 4.16161712] x = [ 3.07507642; 0.58675203; -0.64849988; 5.33343053; 6.66765397; 4.16161712] and the 2 norm of x 10.0221

I am trying to find where the error in my code is but finding it difficult...below is my code

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

How did you compute the true value?

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

When I execute:

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

I get:

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

As you do with Jacobi.

Hope this helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM