• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Nov 22nd, 2019 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import numpy as np
2. import math
3. import matplotlib.pyplot as plt
4.
5. left = -1
6. right = 1
7. k = 1
8. n = 12
9. plt.grid()
10.
11.
12. def phi(x, i):
13.     return x**i * (1 - x ** 2)
14.
15.
16. def a(x):
17.     return math.sin(k)
18.
19.
20. def b(x):
21.     return math.cos(k)
22.
23.
24. def f(x):
25.     return -1
26.
27.
28. def p(x):
29.     return 1 + x * x * b(x)
30.
31.
32. def GetBasisCoefficient(j, x):
33.     if j == 0:
34.         return -2 + (1 - x ** 2) * p(x)
35.     elif j == 1:
36.         return -6 * x + (x - x ** 3) * p(x)
37.     else:
38.         return j * (j - 1) * x ** (j - 2) - (j + 1) * (j + 2) * x ** j \
39.                      + (x ** j - x ** (j + 2)) * p(x)
40.
41.
43.     res = np.linalg.solve(A, y)
44.     func = lambda x: sum(res[i] * (x ** i * (1 - x ** 2)) for i in range(n))
45.     Y = [func(x) for x in X]
46.     plt.plot(X, Y)
47.
48.
49. def SolveCollocation():
50.     X = np.linspace(left, right, n)
51.     y = [f(x) for x in X]
52.     A = [[0] * n for _ in range(n)]
53.     for i in range(n):
54.         for j in range(n):
55.             A[i][j] = GetBasisCoefficient(j, X[i])
57.
58.
59. def SolveLSMIntegral():
60.     X = np.linspace(left, right, n)
61.     h = (right - left) / n
62.     A = [[0] * n for _ in range(n)]
63.     y = [0 for _ in range(n)]
64.     for i in range(n):
65.         y[i] = np.sum(f(X) * GetBasisCoefficient(i, X)) * h
66.         for j in range(n):
67.             A[i][j] = np.sum(GetBasisCoefficient(j, X) * GetBasisCoefficient(i, X)) * h
69.
70.
71. def SolveLSMDiscrete():
72.     X = np.linspace(left, right, n)
73.     A = [[0] * n for _ in range(n)]
74.     y = [0 for _ in range(n)]
75.     for i in range(n):
76.         y[i] = np.sum([f(X) * GetBasisCoefficient(i, X)])
77.         for j in range(n):
78.             A[i][j] = np.sum(GetBasisCoefficient(j, X) * GetBasisCoefficient(i, X))
80.
81.
82. def SolveGalerkin():
83.     X = np.linspace(left, right, n)
84.     A = [[0] * n for _ in range(n)]
85.     h = (right - left) / n
86.     y = [0 for _ in range(n)]
87.     for i in range(n):
88.         y[i] = np.sum(f(X) * phi(X, i)) * h
89.         for j in range(n):
90.             A[i][j] = np.sum(phi(X, i) * GetBasisCoefficient(j, X)) * h