Advertisement
Pug_coder

Untitled

May 7th, 2023
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import math
  2.  
  3.  
  4. def f(x):
  5. #return math.exp(x)
  6. return math.sin(abs(x - 1/2))
  7.  
  8.  
  9. def thomas_algorithm(n, k, y):
  10. a = [1] * n
  11. a[0] = 0
  12. b = [4] * n
  13. c = [1] * n
  14. c[n-1] = 0
  15. d = [0] * n
  16. for i in range(n):
  17. d[i] = k * (y[i+2] - 2 * y[i+1] + y[i])
  18.  
  19. alpha = [0] * n
  20. beta = [0] * n
  21. x = [0] * n
  22.  
  23. alpha[0] = - c[0] / b[0]
  24. beta[0] = d[0] / b[0]
  25.  
  26. for i in range(1, n):
  27. alpha[i] = - c[i] / (a[i] * alpha[i-1] + b[i])
  28. beta[i] = (d[i] - a[i] * beta[i-1]) / (a[i] * alpha[i-1] + b[i])
  29.  
  30. x[n-1] = beta[n-1]
  31. for i in range(n-2, -1, -1):
  32. x[i] = alpha[i] * x[i+1] + beta[i]
  33.  
  34. return [0] + x + [0]
  35.  
  36.  
  37. def coefficients_calculation(h, c, y, n):
  38. a = [0] * n
  39. b = [0] * n
  40. d = [0] * n
  41. for i in range(1, n):
  42. a[i-1] = y[i-1]
  43. b[i-1] = (y[i] - y[i-1]) / h - h * (c[i] + 2 * c[i-1]) / 3
  44. d[i-1] = (c[i] - c[i-1]) / (3 * h)
  45.  
  46. return a, b, d
  47.  
  48.  
  49. if __name__ == '__main__':
  50. x0 = 0
  51. xn = 1
  52. n = 10
  53. h = (xn - x0) / n
  54.  
  55. x = [0] * (n+1)
  56. y = [0] * (n+1)
  57.  
  58. for i in range(n+1):
  59. x[i] = x0 + i * h
  60. y[i] = f(x[i])
  61.  
  62. c = thomas_algorithm(n-1, 3 / h ** 2, y)
  63. a, b, d = coefficients_calculation(h, c, y, n+1)
  64.  
  65. with open('test.txt', 'w') as t:
  66. for i in range(2*n+1):
  67. xi = x0 + 0.5 * i * h
  68. ind = i // 2
  69. if ind == n:
  70. ind -= 1
  71. spline_x = a[ind] + b[ind] * (xi - x[ind]) + c[ind] * (xi - x[ind]) ** 2 + d[ind] * (xi - x[ind]) ** 3
  72. yi = f(xi)
  73. s = "x=%f | spl(x) = %f | f(x) = %f | %f" % (xi, spline_x, yi, spline_x - yi)
  74. t.write(s)
  75. t.write('\n')
  76.  
  77. with open('test.txt','r') as t:
  78. for i, line in enumerate(t):
  79. print(i, line)
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement