Order of accuracy Finite Difference Boundary Value Problem

25 Views Asked by At

I have implemented a finite difference solver for poissons equation with dirichlet boundary conditions, but the issue is that I am getting first order accuracy ($O(h)$), but I expect to get two($O(h^2)$), Here is the code:

def solve_1d_bvp(f ,n, a, b, boundary_conditions):
    dx = (b-a)/n
    xx = np.linspace(a,b,n)
    X = np.zeros(n-2,dtype=np.float64)
    A = np.diag(np.ones(n-3,dtype=np.float64),-1) + np.diag(-2*np.ones(n-2,dtype=np.float64)) + np.diag(np.ones(n-3,dtype=np.float64),1)
    X[0] = (dx**2)*f(xx[1]) - boundary_conditions[0]
    X[1:-1] = (dx**2 )* f(xx[2:-2])
    X[-1] = (dx**2)*f(xx[-2]) - boundary_conditions[1]
    Y = np.linalg.solve(A,X)
    Y = [boundary_conditions[0] , *Y.flatten(), boundary_conditions[1]]
    return xx, Y

and here is how I compute the error

error = []
spacing = np.array([2**i for i in range(3,10)])
for n in spacing:
    xx , Y = solve_1d_bvp(f, v, w, n, a, b, boundary_conditions)
    the_error =  np.linalg.norm(np.abs(Y - (0.5*xx*(xx-1)))  ,ord = np.inf )
    error.append(the_error)
m,c = np.polyfit( np.log((b-a)/spacing),np.log(error), 1)
print(np.log((b-a)/spacing),np.log(error))
plt.loglog((b-a)/spacing,error,base = 3, color = "blue", marker = "o", markersize = 5)
plt.xlabel("h")
plt.ylabel("error")
plt.show()
display(m,c)

Any help will be appreciated.