Advertisement
Guest User

task6

a guest
May 24th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. import numpy as np
  2. from scipy import integrate
  3. from scipy.special import jacobi
  4. from tabulate import tabulate
  5.  
  6. a = -1.0
  7. b = 1.0
  8.  
  9. Q1 = np.poly1d([1, 1.5, 0, -14.5])
  10. Q2 = np.poly1d([1, 2, -11])
  11.  
  12.  
  13. def f(x):
  14.     return 1. - x / 2.
  15.  
  16.  
  17. def points(n):
  18.     return np.linspace(a, b, n)
  19.  
  20.  
  21. def colloc_points(n):
  22.     return [np.cos(((2 * i - 1) * np.pi) / (2 * n)) for i in range(1, n + 1)]
  23.  
  24.  
  25. def w(n):
  26.     if n == 1:
  27.         return [Q1]
  28.     elif n == 2:
  29.         return [Q1, Q2]
  30.     else:
  31.         jacobi_tail = [np.poly1d([1, 0, -2, 0, 1]) *
  32.                        jacobi(i - 3, 2, 2) for i in range(3, n + 1)]
  33.         return [Q1, Q2] + jacobi_tail
  34.  
  35.  
  36. def L_diff(w, x):
  37.     w_2 = np.polyder(w, 2)
  38.     w_1 = np.polyder(w, 1)
  39.     ans = -1 / (3 + np.sin(x)) * w_2(x) - x * w_1(x) + (1 + x) * w(x)
  40.     return ans
  41.  
  42.  
  43. def L_colloc(n):
  44.     L = np.zeros((n, n))
  45.     g = np.zeros(n)
  46.     W = w(n)
  47.     X = colloc_points(n)
  48.  
  49.     for i in range(0, n):
  50.         for j in range(0, n):
  51.             L[i, j] = L_diff(W[j], X[i])
  52.         g[i] = f(X[i])
  53.     return L, g
  54.  
  55.  
  56. def L_gal(n):
  57.     L = np.zeros((n, n))
  58.     g = np.zeros(n)
  59.     W = w(n)
  60.  
  61.     for j in range(0, n):
  62.         for i in range(0, n):
  63.             L[j, i] = integrate.quad(lambda x: W[j](x) * L_diff(W[i], x), a, b)[0]
  64.         g[j] = integrate.quad(lambda x: W[j](x) * f(x), a, b)[0]
  65.     return L, g
  66.  
  67.  
  68. def coeff(l, n):
  69.     L, g = l(n)
  70.     return np.linalg.solve(L, g)
  71.  
  72.  
  73. def solution(W, C, n):
  74.     return lambda x: np.dot(np.array([W[i](x) for i in range(0, n)]), C)
  75.  
  76.  
  77. def print_table(n, a, b, l):
  78.     print((' ' * 6) + "|" + (' ' * 14) + 'y_n(x)' + (' ' * 16))
  79.     table = []
  80.     for i in range(3, n + 1):
  81.         W = w(i)
  82.         C = coeff(l, i)
  83.         sol = solution(W, C, i)
  84.         table.append([i, sol(a), sol((a + b) / 2), sol(b)])
  85.  
  86.     head = ['x = {0}'.format(a), 'x = {0}'.format((a + b) / 2), 'x = {0}'.format(b)]
  87.     print(tabulate(table, headers=['n'] + head * 2, tablefmt="grid", floatfmt="f"))
  88.  
  89. print('Galerkin method')
  90. print('')
  91. print_table(7, a, b, L_gal)
  92. print('')
  93.  
  94. print('Collocation method')
  95. print('')
  96. print_table(7, a, b, L_colloc)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement