You are on page 1of 2

import numpy as np

import matplotlib.pyplot as plt

import math

def f(x, y):

return np.sin(2 * x) + x**2

a=0

b=1

n = 10

h = (b - a) / (n + 1)

x = np.linspace(a, b, n + 2)

u = np.zeros(n + 2)

# Perform FDM iterations

for i in range(1, n + 1):

u[i] = (u[i+1] + u[i-1] - h**2 * f(x[i], u[i])) / 2

# Exact solution by integrating over two times PDE

def exact_solution(x):

return -x**2/4 + (x*np.sin(2*x))/4 - (1/16)*(np.sin(2*x) - 4*x)

delta = np.abs(u - exact_solution(x))

avg_error = np.mean(np.abs(u - exact_solution(x)))

print("Exact:",exact_solution(x))

print("FDM:",u)

print("Delta:",delta)

print("Delta_avg:",avg_error)
plt.figure(figsize=(10, 6))

plt.plot(x, u, label="Approximate Solution (FDM)")

plt.plot(x, exact_solution(x), label="Exact Solution")

plt.xlabel("x")

plt.ylabel("u")

plt.legend()

plt.title(f"FDM Solution vs. Exact Solution")

plt.grid(True)

plt.show()

You might also like