Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. import numpy as np
  2.  
  3. tau = 2 * np.pi
  4. tau2 = tau * tau
  5. i = complex(0,1)
  6.  
  7. def solution_f(t, x):
  8. return 0.5 * (np.exp(-tau * i * x) * np.exp((2 - tau2) * i * t) + np.exp(tau * i * x) * np.exp((tau2 + 4) * i * t))
  9.  
  10. def solution_g(t, x):
  11. return 0.5 * (np.exp(-tau * i * x) * np.exp((2 - tau2) * i * t) - np.exp(tau * i * x) * np.exp((tau2 + 4) * i * t))
  12.  
  13. for l in range(2, 12):
  14. N = 2 ** l #number of grid points
  15. dx = 1.0 / N #space between grid points
  16. dx2 = dx * dx
  17. dt = dx #time step
  18. t_final = 1
  19. approximate_f = np.zeros((N, 1), dtype = np.complex)
  20. approximate_g = np.zeros((N, 1), dtype = np.complex)
  21.  
  22. #Insert initial conditions
  23. for k in range(N):
  24. approximate_f[k, 0] = np.cos(tau * k * dx)
  25. approximate_g[k, 0] = -i * np.sin(tau * k * dx)
  26.  
  27. #Create coefficient matrix
  28. A = np.zeros((2 * N, 2 * N), dtype = np.complex)
  29.  
  30. #First row is special
  31. A[0, 0] = 1 -3*i*dt
  32. A[0, N] = ((2 * dt / dx2) + dt) * i
  33. A[0, N + 1] = (-dt / dx2) * i
  34. A[0, -1] = (-dt / dx2) * i
  35.  
  36. #Last row is special
  37. A[N - 1, N - 1] = 1 - (3 * dt) * i
  38. A[N - 1, N] = (-dt / dx2) * i
  39. A[N - 1, -2] = (-dt / dx2) * i
  40. A[N - 1, -1] = ((2 * dt / dx2) + dt) * i
  41.  
  42. #middle
  43. for k in range(1, N - 1):
  44. A[k, k] = 1 - (3 * dt) * i
  45. A[k, k + N - 1] = (-dt / dx2) * i
  46. A[k, k + N] = ((2 * dt / dx2) + dt) * i
  47. A[k, k + N + 1] = (-dt / dx2) * i
  48.  
  49. #Bottom half
  50. A[N :, :N] = A[:N, N:]
  51. A[N:, N:] = A[:N, :N]
  52.  
  53. Ainv = np.linalg.inv(A)
  54.  
  55. #Advance through time
  56. time = 0
  57. while time < t_final:
  58. b = np.concatenate((approximate_f, approximate_g), axis = 0)
  59. x = np.dot(Ainv, b) #Solve Ax = b
  60. approximate_f = x[:N]
  61. approximate_g = x[N:]
  62. time += dt
  63. approximate_solution = np.concatenate((approximate_f, approximate_g), axis=0)
  64.  
  65. #Calculate the actual solution
  66. actual_f = np.zeros((N, 1), dtype = np.complex)
  67. actual_g = np.zeros((N, 1), dtype = np.complex)
  68. for k in range(N):
  69. actual_f[k, 0] = solution_f(t_final, k * dx)
  70. actual_g[k, 0] = solution_g(t_final, k * dx)
  71. actual_solution = np.concatenate((actual_f, actual_g), axis = 0)
  72.  
  73. print(np.sqrt(dx) * np.linalg.norm(actual_solution - approximate_solution))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement