在python中生成随机矩阵

时间:2018-10-17 19:50:47

标签: python matrix numerical-methods

在下面的代码中,我对普通的平方线性系统Ax = b进行了部分枢轴化,实现了高斯消去。我已经测试了我的代码,并产生了正确的输出。但是,现在我正在尝试执行以下操作,但是我不太确定如何编写代码,以寻求帮助!

我想通过解决Ax = b来测试我的实现,其中A是随机100x100矩阵,b是随机100x1向量。

在我的代码中,我放入了矩阵

A = np.array([[3.,2.,-4.],[2.,3.,3.],[5.,-3.,1.]])

b =  np.array([[3.],[15.],[14.]])

并获得以下正确的输出:

[3. 1. 2.]
[3. 1. 2.]

但是现在如何更改它以生成随机矩阵?

下面是我的代码:

import numpy as np
def GEPP(A, b, doPricing = True):
    '''
    Gaussian elimination with partial pivoting.
    input: A is an n x n numpy matrix
           b is an n x 1 numpy array
    output: x is the solution of Ax=b 
        with the entries permuted in 
        accordance with the pivoting 
        done by the algorithm
    post-condition: A and b have been modified.
    '''
    n = len(A)
    if b.size != n:

        raise ValueError("Invalid argument: incompatible sizes between"+

                     "A & b.", b.size, n)

    # k represents the current pivot row. Since GE traverses the matrix in the 

    # upper right triangle, we also use k for indicating the k-th diagonal 

    # column index.

    # Elimination

    for k in range(n-1):

        if doPricing:

            # Pivot

            maxindex = abs(A[k:,k]).argmax() + k

            if A[maxindex, k] == 0:


                raise ValueError("Matrix is singular.")

            # Swap

            if maxindex != k:

                A[[k,maxindex]] = A[[maxindex, k]]

                b[[k,maxindex]] = b[[maxindex, k]]

        else:

            if A[k, k] == 0:

                raise ValueError("Pivot element is zero. Try setting doPricing to True.")

       #Eliminate

       for row in range(k+1, n):

           multiplier = A[row,k]/A[k,k]

           A[row, k:] = A[row, k:] - multiplier*A[k, k:]

           b[row] = b[row] - multiplier*b[k]

    # Back Substitution

    x = np.zeros(n)

    for k in range(n-1, -1, -1):

        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]

    return x



if __name__ == "__main__":

    A = np.array([[3.,2.,-4.],[2.,3.,3.],[5.,-3.,1.]])

    b =  np.array([[3.],[15.],[14.]])

    print (GEPP(np.copy(A), np.copy(b), doPricing = False))

    print (GEPP(A,b))

5 个答案:

答案 0 :(得分:3)

您已经在使用numpy。您是否考虑过np.random.rand

np.random.rand(m, n)将为您提供一个值为[0,1)的随机矩阵。您可以通过乘以随机值或舍入来进一步处理它。

编辑:类似这样的东西

if __name__ == "__main__":
    A = np.round(np.random.rand(100, 100)*10)
    b =  np.round(np.random.rand(100)*10)
    print (GEPP(np.copy(A), np.copy(b), doPricing = False))
    print (GEPP(A,b))

答案 1 :(得分:2)

因此,我将为此使用np.random.randint

numpy.random.randint(low, high=None, size=None, dtype='l')

会从适当的分布中输出一个大小为形状的随机整数数组,如果未提供大小,则为单个此类int。

low是您希望在范围内的整数的下限

high比所需范围的上限大一。

size是输出数组的尺寸

dtype是结果的dtype

所以如果我是你,我会写

A = np.random.randint(0, 11, (100, 100))
b = np.random.randint(0, 11, 100)

答案 2 :(得分:1)

基本上,您可以使用1创建所需的矩阵,然后对其进行迭代,例如将每个值设置为random.randint(0,100)

带1的空矩阵是:

one_array = np.ones((100, 100))

编辑:

喜欢:

for x in one_array.shape[0]:
    for y in one_array.shape[1]:
        one_array[x][y] = random.randint(0, 100)

答案 3 :(得分:1)

A = np.random.normal(size=(100,100))
b = np.random.normal(size=(100,1))
x = np.linalg.solve(A,b)
assert max(abs(A@x - b)) < 1e-12

很明显,您可以使用与normal不同的分布,例如uniform

答案 4 :(得分:1)

您可以使用numpy的本地rand函数:

np.random.rand()

在您的代码中,只需将A和b定义为:

A = np.random.rand(100, 100)
b = np.random.rand(100)

这将生成100x100矩阵和100x1向量(均为numpy数组),其中填充了0到1之间的随机值。

有关此功能,请参见docs,以了解更多信息。