更新:代码中ii和jj的顺序反了
import numpy as np
from matplotlib import pyplot as plt
from scipy.sparse import diags, lil_matrix
from scipy.sparse.linalg import spsolve
def FDM_poison(div_f, x, y):
ii, jj = div_f.shape
ii2 = ii - 2
jj2 = jj - 2
hx = np.mean(x[1:]-x[:-1])
hy = np.mean(y[1:]-y[:-1])
print('hx=', hx, 'hy=', hy)
A = lil_matrix((ii2 * jj2, ii2 * jj2))
diagonals = [2 * (1/hx**2 + 1/hy**2) * np.ones(jj2),
-1/hy**2 * np.ones(jj2-1),
-1/hy**2 * np.ones(jj2-1)]
Dmatrix = diags(diagonals, [0, 1, -1])
for k in range(ii2):
p = slice(k * jj2, (k + 1) * jj2)
A[p, p] = Dmatrix
if k < ii2 - 1:
next_p = slice((k + 1) * jj2, (k + 2) * jj2)
A[p, next_p] = diags([-1/hx**2 * np.ones(jj2)], [0])
A[next_p, p] = diags([-1/hx**2 * np.ones(jj2)], [0])
A =