【问题标题】:Why are my answer's decimals incorrect in Python?为什么我的答案在 Python 中的小数点不正确?
【发布时间】:2020-09-20 20:15:52
【问题描述】:

我目前正忙于一个问题,需要使用 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))

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    你是如何计算真实值的?

    问题说明当 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]]
    

    就像你对 Jacobi 所做的那样。

    希望这会有所帮助:)

    【讨论】:

    • 这是一种更简单的写法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    相关资源
    最近更新 更多