Advertisement
mirosh111000

Iнтерполяцiя кубiчним сплайном

May 22nd, 2023
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. def tridiagonal_solve(a, b, c, d):
  5. n = len(d)
  6. c_ = np.zeros(n)
  7. d_ = np.zeros(n)
  8. x = np.zeros(n)
  9.  
  10. c_[0] = c[0] / b[0]
  11. d_[0] = d[0] / b[0]
  12.  
  13. for i in range(1, n):
  14. c_[i] = c[i] / (b[i] - a[i] * c_[i - 1])
  15. d_[i] = (d[i] - a[i] * d_[i - 1]) / (b[i] - a[i] * c_[i - 1])
  16.  
  17. x[n - 1] = d_[n - 1]
  18.  
  19. for i in range(n - 2, -1, -1):
  20. x[i] = d_[i] - c_[i] * x[i + 1]
  21.  
  22. return x
  23.  
  24. def cubic_spline(x, y):
  25. n = len(x)
  26. h = np.diff(x)
  27. alpha = np.zeros(n)
  28. for i in range(1, n - 1):
  29. alpha[i] = (3 / h[i]) * (y[i + 1] - y[i]) - (3 / h[i - 1]) * (y[i] - y[i - 1])
  30. L = np.zeros(n)
  31. mu = np.zeros(n)
  32. z = np.zeros(n)
  33. c = np.zeros(n)
  34.  
  35. L[0] = 1.0
  36. mu[0] = 0.0
  37. z[0] = 0.0
  38.  
  39. for i in range(1, n - 1):
  40. L[i] = 2.0 * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1]
  41. mu[i] = h[i] / L[i]
  42. z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / L[i]
  43.  
  44. L[n - 1] = 1.0
  45. z[n - 1] = 0.0
  46. c[n - 1] = 0.0
  47.  
  48. for j in range(n - 2, -1, -1):
  49. c[j] = z[j] - mu[j] * c[j + 1]
  50. b = np.zeros(n - 1)
  51. d = np.zeros(n - 1)
  52. for i in range(n - 1):
  53. b[i] = (y[i + 1] - y[i]) / h[i] - (h[i] * (c[i + 1] + 2 * c[i])) / 3
  54. d[i] = (c[i + 1] - c[i]) / (3 * h[i])
  55.  
  56. return b, c, d
  57.  
  58. def evaluate_cubic_spline(x, y, b, c, d, query_points):
  59. results = []
  60. for query in query_points:
  61. for i in range(len(x) - 1):
  62. if x[i] <= query <= x[i + 1]:
  63. dx = query - x[i]
  64. result = y[i] + b[i] * dx + c[i] * dx**2 + d[i] * dx**3
  65. results.append(result)
  66. break
  67.  
  68. return results
  69.  
  70. def func(x):
  71. return 1 / (13 + 25 * x**2) - 13
  72.  
  73. A = -1
  74. B = 1
  75. N = 7
  76.  
  77. x = np.linspace(A, B, N)
  78. y = func(x)
  79.  
  80. b, c, d = cubic_spline(x, y)
  81.  
  82. X = np.linspace(A, B, 1000)
  83.  
  84. Y = evaluate_cubic_spline(x, y, b, c, d, X)
  85.  
  86. plt.plot(X, func(X), label='y=1/(13+25x^2) - 13', lw=3.5)
  87. plt.plot(X, Y, 'r--', label='Кубічний сплайн')
  88. plt.plot(x, y, 'yo', label='Точки даних')
  89. plt.xlabel('x')
  90. plt.ylabel('y')
  91. plt.legend()
  92. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement