python - 我的代码在创建这个矩阵时哪里出了问题?

标签 python

我正在尝试解决以下问题:

Consider the n simultaneous equations Ax=b, where

A_(ij) = (i+j)^2 and b_i = sum(A_ij) from j=0 to n, with i=0,1,...,n, j=0,1,...,n.

Write an program that solves these equations for any given n.

所以我应该创建矩阵 A 和向量 b,然后用它们来求解 Ax=b。我可以创建 A,它是使用以下代码完成的:

A = numpy.zeros(n*n).reshape(n,n)
def matrix(n):
    for i in range(0,n):
        for j in range(0,n):
            A[i,j] = (i+j)**2

matrix(n)
print A

对于任何选择的 n,这给了我一个漂亮的 nxn 矩阵。然而,我现在正在努力创建向量 b。这是我到目前为止的代码:

b = numpy.zeros(n*1).reshape(n,1)
def sumRow(n):
    while i = 0:
        for j in range(0,n):
            b[i] = math.fsum(A[i,j])
sumRow(n)
print b         

首先,我不知道如何从 i=0 到 i=n。

运行此代码时我也遇到错误,我正在努力解决该错误。

我的思考过程如下:

  1. 我创建了一个由零组成的 nx1 向量。
  2. 然后,我在 n 中定义一个函数,将其命名为 sumRow。
  3. 然后我告诉函数按照 b 的公式执行操作。
  4. 对于第 0 行和第 0 到 n 范围内的 j,我告诉计算机将 b 的第 i 行设为 A 第 i 行中所有数字的总和。

有人可以帮我修改第二个代码块,以获得给定 n 的矩阵 b。

最佳答案

这应该可以解决您填充向量b-

的问题
b = numpy.zeros(n*1).reshape(n,1)
def sumRow(n):
    for i in range(0,n):
        b[i] = math.fsum(A[i]) //calculates the sum of all elements of the given row
sumRow(n)
print b

关于python - 我的代码在创建这个矩阵时哪里出了问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311471/

相关文章:

python - 使用 Python 检查 PDF 文件是否有效

python - 当存在特定匹配时,将数据框的一列添加到另一个数据框

python - 使用 BeautifulSoup 在 Python 中进行抓取

python - 类型错误 : unsupported operand type(s) for *: 'dict' and 'int'

python - 在元组或对象列表上使用 Python 的 list index() 方法?

python - 数据库错误 : Write pandas dataframe to vertica using to_sql and vertica_python

python - 如何在 Python 中将新行附加到旧的 CSV 文件?

python无法在表中插入字符串

python - 比较Python中两个列表的项目

python - 如何hstack numpy记录数组?