Advertisement
daegron

specialForElena

Mar 28th, 2023
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. # Define the problem parameters
  5. def p(x):
  6.     return 1.0
  7.  
  8. def q(x):
  9.     return 1.0
  10.  
  11. def r(x):
  12.     return x
  13.  
  14. def f(x):
  15.     return np.exp(x)
  16.  
  17. # Set up the grid
  18. a = 0.0
  19. b = 1.0
  20. N = 10  # initial number of grid points
  21. x = np.linspace(a, b, N)
  22.  
  23. # Discretize the differential equation
  24. h = x[1] - x[0]
  25. A = np.zeros((N, N))
  26. b = np.zeros(N)
  27. for i in range(1, N - 1):
  28.     A[i, i - 1] = -p(x[i]) / h**2 - q(x[i]) / (2 * h)
  29.     A[i, i] = 2 * p(x[i]) / h**2 + r(x[i])
  30.     A[i, i + 1] = -p(x[i]) / h**2 + q(x[i]) / (2 * h)
  31.     b[i] = f(x[i])
  32.  
  33. # Set up the boundary conditions
  34. A[0, 0] = 1.0
  35. A[N - 1, N - 1] = 1.0
  36. b[0] = 0.0
  37. b[N - 1] = 0.0
  38.  
  39. # Solve the linear system
  40. y = np.linalg.solve(A, b)
  41.  
  42. # Refine the grid using Richardson extrapolation
  43. M = 2 * N  # number of points on the refined grid
  44. x_ = np.linspace(a, b, M)
  45. h_ = x_[1] - x_[0]
  46. A_ = np.zeros((M, M))
  47. b_ = np.zeros(M)
  48. for i in range(1, M - 1):
  49.     A_[i, i - 1] = -p(x_[i]) / h_**2 - q(x_[i]) / (2 * h_)
  50.     A_[i, i] = 2 * p(x_[i]) / h_**2 + r(x_[i])
  51.     A_[i, i + 1] = -p(x_[i]) / h_**2 + q(x_[i]) / (2 * h_)
  52.     b_[i] = f(x_[i])
  53. A_[0, 0] = 1.0
  54. A_[M - 1, M - 1] = 1.0
  55. b_[0] = 0.0
  56. b_[M - 1] = 0.0
  57. y_ = np.linalg.solve(A_, b_)
  58.  
  59. # Check the convergence rate
  60. err = np.abs(y_ - y[::2])
  61. h = h_[::2]
  62. plt.loglog(h, err, '-o')
  63. plt.xlabel('h')
  64. plt.ylabel('error')
  65. plt.show()
  66.  
  67. # Output the solution
  68. plt.plot(x, y, '-o', label='coarse grid')
  69. plt.plot(x_, y_, '-o', label='refined grid')
  70. plt.legend()
  71. plt.xlabel('x')
  72. plt.ylabel('y')
  73. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement