我正在尝试计算这个稀疏矩阵问题 Au=f 的近似解,但我在矩阵的输出中得到“nan”而不是矩阵元素,尽管输入矩阵都包含 np.float64。 我不明白我哪里错了。
这是我的代码:-
import numpy as np
import scipy
from scipy.sparse import coo_matrix
from scipy.sparse import random
#Defining a function that takes N as an input
def our_func (N) :
#Taking the given values of parameters h and k
h = 1/N
k = (29*(np.pi))/2
#Defining initial input matrix with domensions N+1
I = np.empty([N+1,N+1], dtype=np.float64)
#[REF :- https://www.geeksforgeeks.org/how-to-create-an-empty-matrix-with-numpy-in-python/]
print("datatype of I is :-")
print(I.dtype)
#Generating the matrix A in coo sparse format
A_coo = coo_matrix(I).reshape((N+1,N+1))
print("datatype of A_coo is :-")
print(A_coo.dtype)
#Converting the matrix A from coo sparse format to CSR sparse format
A = A_coo.tocsr().reshape((N+1,N+1))
print("datatype of A is :-")
print(A.dtype)
# Creating an empty storage array for the right side of our equation Au=f
f = np.empty((N+1), dtype=np.float64)
#The rows of matrix A and f are defined as :-
A[0,0] = 1 #for i==j==0
A[N,N] = 1 #for i==j==N
f[N] = 1 #for i==N
f[0] = 0 #for i==0
for i in range (int(N)) :
for j in range (int(N)) :
A[i,1] = 2 - ((h**2)*(k**2))
A[i,i+1] = -1
A[i,i-1] = -1
A[i,j] = 0 #for i!==j
#Our function Returns matrix A and f, with matrix A in sparse storage format
return A, f
# Defining a new function using the function scipy.sparse.linalg.spsolve
# to solve the sparse matrix-vector problem: Au=f
def our_solution(N):
A,f = our_func(N)
our_sparse_matrix = scipy.sparse.linalg.spsolve(A,f)
return our_sparse_matrix
# Using this defined function to compute the approximate solution for our
# problem, for N=10, N=100, and N=1000.
approx_sol_1 = our_solution(10)
print("approx_sol_1 is :- ")
print(approx_sol_1)
运行较小的函数
N
:
In [4]: A,f = our_func(10)
datatype of I is :-
float64
datatype of A_coo is :-
float64
datatype of A is :-
float64
C:\Users\14256\miniconda3\lib\site-packages\scipy\sparse\_index.py:103: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
self._set_intXint(row, col, x.flat[0])
它警告我们,单独设置稀疏
csr
数组的元素效率不高。
In [5]: A
Out[5]:
<11x11 sparse matrix of type '<class 'numpy.float64'>'
with 103 stored elements in Compressed Sparse Row format>
请注意,矩阵并不是特别稀疏,121 个可能值中有 103 个非零。
In [6]: A.A
Out[6]:
array([[ 0. , -1. , 0. , 0. ,
0. , 0. , 0. , 0. ,
0. , 0. , -1. ],
[ -1. , -18.75084325, -1. , 0. ,
0. , 0. , 0. , 0. ,
0. , 0. , 0. ],...
它可以被修剪,去掉很多0。
In [10]: A.eliminate_zeros()
In [11]: A
Out[11]:
<11x11 sparse matrix of type '<class 'numpy.float64'>'
with 28 stored elements in Compressed Sparse Row format>