Advertisement
mirosh111000

Чисельне диференцiювання

May 23rd, 2023
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.31 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4.  
  5.  
  6. def f(x):
  7.     return 1 / (x + 13)
  8.  
  9. def diff1(x):
  10.     return - 1 / ((x + 13)**2)
  11.  
  12. def diff2(x):
  13.     return 2 / ((x + 13)**3)
  14.  
  15. def factorial(n):
  16.     if n == 0:
  17.         return 1
  18.     else:
  19.         return n * factorial(n-1)
  20.  
  21. def polinom_newton(x, y, new_x, h):
  22.  
  23.     N = len(x)
  24.  
  25.  
  26.     xy_df = []
  27.     for i in range(N):
  28.         xy_df.append([x[i], y[i]])
  29.     df1 = pd.DataFrame(data=xy_df, columns=['x', 'y'])
  30.  
  31.     diff = np.zeros((N, N - 1), dtype=float)
  32.     for i in range(N - 1):
  33.         diff[i][0] = y[i + 1] - y[i]
  34.     for k in range(1, N-1):
  35.         for i in range(N - (k + 1)):
  36.             diff[i][k] = diff[i + 1][k - 1] - diff[i][k - 1]
  37.  
  38.     df2 = pd.DataFrame(data=diff, columns=[f'delta{i}_y' for i in range(1, N)])
  39.     df = df1.join(df2)
  40.     df.index = ['' for i in range(N)]
  41.  
  42.     if abs(new_x - x.min()) < abs(new_x - x.max()):
  43.         t = (new_x - x[0]) / h
  44.         u = 1
  45.         s = df.iloc[0, 1]
  46.         for i in range(N-1):
  47.             u = u * (t - i) / factorial(i + 1)
  48.             s = s + u * df.iloc[0, i+2]
  49.  
  50.         diff_1 = ( df.iloc[0, 2] + df.iloc[0, 3]*(2*t - 1)/2 + df.iloc[0, 4]*(3*t**2 - 6*t + 2)/6 + df.iloc[0, 5]*(4*t**3 - 18*t**2 + 22*t - 6)/24 + df.iloc[0, 6]*(5*t**4 - 40*t**3 + 105*t**2 - 100*t + 24)/120 ) / h
  51.         diff_2 = ( df.iloc[0, 3] + df.iloc[0, 4]*(t - 1) + df.iloc[0, 5]*(12*t**2 - 36*t + 22)/24 + df.iloc[0, 6]*(20*t**3 - 120*t**2 + 210*t - 100)/120 ) / h**2
  52.  
  53.     else:
  54.         t = (new_x - x[-1]) / h
  55.         u = 1
  56.         s = df.iloc[-1, 1]
  57.         for i in range(N-1):
  58.             u = u * (t + i) / factorial(i + 1)
  59.             s = s + u * df.iloc[N-1-(i+1), i+2]
  60.  
  61.         diff_1 = (df.iloc[N-2, 2] + df.iloc[N-3, 3]*(2 * t + 1)/2 + df.iloc[N-4, 4]*(3 * t ** 2 + 6 * t + 2)/6 + df.iloc[N-5, 5]*(4*t** 3 + 18*t**2 + 22*t + 6)/12 + df.iloc[N-6, 6] * (5*t**4 + 40*t**3 + 105*t**2 + 100*t + 24) / 120) / h
  62.         diff_2 = (df.iloc[N-3, 3] + df.iloc[N-4, 4]*(t + 1) + df.iloc[N-5, 5]*(6*t**2 + 18*t + 11)/12 + df.iloc[N-6, 6]*(20*t**3 + 120*t**2 + 210*t + 100)/120 ) / (h ** 2)
  63.     # print(f'new_x = {new_x}')
  64.     # print(f'new_y = {s}')
  65.  
  66.  
  67.     return (df, s, diff_1, diff_2)
  68.  
  69. def grafic():
  70.     X = np.linspace(x.min() - 1, x.max() + 1, 100)
  71.     Y = np.zeros(len(X))
  72.     for i in range(len(X)):
  73.         Y[i] = polinom_newton(x, y, X[i], h=h)[1]
  74.     plt.title("f(x)")
  75.     plt.xlabel("x")
  76.     plt.ylabel("y")
  77.     plt.grid()
  78.     plt.plot(X, Y, label="Iнтерполяцiйний полiном Ньютона")
  79.     plt.plot(x, y, 'ro', label='Початкові точки')
  80.     plt.legend()
  81.     plt.show()
  82.  
  83. def df_with_new_x(X):
  84.  
  85.     df = pd.DataFrame(columns=['x','y', 'diif1', 'diff2'])
  86.     for i in range(0, len(X)):
  87.         tabl, y1, diff1, diff2 = polinom_newton(x, y, X[i], h=h)
  88.         df.loc[i+1] = [X[i], y1, diff1, diff2]
  89.     return df
  90.  
  91.  
  92. def abs_err(X, h):
  93.     return abs(polinom_newton(x, y, new_x=X, h=h)[1] - f(X))
  94.  
  95. def rel_err(X, h):
  96.     return abs(abs_err(X, h) / f(X))
  97.  
  98. def prava_rizn(x, h):
  99.     return ( f(x+h) - f(x) ) / h
  100.  
  101. def center_rizn_diff1(x, h):
  102.     return ( f(x+h) - f(x-h) ) / (2*h)
  103.  
  104. def center_rizn_diff2(x, h):
  105.     return (f(x + h) - 2*f(x) + f(x-h) ) / (h**2)
  106.  
  107. def abs_err_diff1(x, h):
  108.     return abs(diff1(x) - center_rizn_diff2(x, h))
  109.  
  110. def rel_err_diff1(x, h):
  111.     return abs_err_diff1(x, h) / abs(diff1(x))
  112.  
  113. def abs_err_diff2(x, h):
  114.     return abs(diff2(x) - center_rizn_diff2(x, h))
  115.  
  116. def rel_err_diff2(x, h):
  117.     return abs_err_diff2(x, h) / abs(diff2(x))
  118.  
  119. def err(X, h):
  120.  
  121.     df = pd.DataFrame(columns=[''])
  122.     df.loc['Абсолютна похибка'] = [abs_err(X, h)]
  123.     df.loc['Відносна похибка'] = [rel_err(X, h)]
  124.     df.loc['Права різниця'] = [prava_rizn(X, h)]
  125.     df.loc['Центральна різниця першої похідної'] = [center_rizn_diff1(X, h)]
  126.     df.loc['Центральна різниця другої похідної'] = [center_rizn_diff2(X, h)]
  127.     df.loc['Абсолютна похибка першої похідної'] = [abs_err_diff1(X, h)]
  128.     df.loc['Відносна похибка першої похідної'] = [rel_err_diff1(X, h)]
  129.     df.loc['Абсолютна похибка другої похідної'] = [abs_err_diff2(X, h)]
  130.     df.loc['Відносна похибка другої похідної'] = [rel_err_diff2(X ,h)]
  131.     df.columns = [f'x = {X}; h = {h}']
  132.  
  133.     return df
  134.  
  135.  
  136. h = 0.5
  137. x = np.arange(0, 10.5, h)
  138. y = f(x)
  139.  
  140. table_x_y = pd.DataFrame(data={'x': x, 'y': y}, index=[i+1 for i in range(len(x))])
  141. print(table_x_y)
  142. x1 = 2
  143. x2 = 8
  144. x3 = 1.05
  145. # grafic()
  146.  
  147. X = [x1, x2, x3]
  148.  
  149. new_x = df_with_new_x(X)
  150. print(new_x, '\n')
  151.  
  152. X1 = err(x1, h)
  153. X2 = err(x2, h)
  154. print(X1, '\n')
  155. print(X2, '\n')
  156.  
  157. zavd3_1 = err(x1, 1)
  158. zavd3_2 = err(x1, 2)
  159. zavd3_3 = err(x2, 1)
  160. zavd3_4 = err(x2, 2)
  161. print(zavd3_1, '\n')
  162. print(zavd3_2, '\n')
  163. print(zavd3_3, '\n')
  164. print(zavd3_4, '\n')
  165.  
  166. x = np.arange(0, 5.5, 0.5)
  167. y = f(x)
  168.  
  169. table_x_y = pd.DataFrame(data={'x': x, 'y': y}, index=[i+1 for i in range(len(x))])
  170. print(table_x_y)
  171. x1 = 2
  172. x2 = 8
  173. x3 = 1.05
  174. # grafic()
  175.  
  176. X = [x1, x2, x3]
  177.  
  178. new_x = df_with_new_x(X)
  179. new_x['y_exact'] = [f(x1), f(x2), f(x3)]
  180. print(new_x, '\n')
  181.  
  182. X1 = err(x1, h)
  183. X2 = err(x2, h)
  184. X3 = err(x3, h)
  185. print(X1, '\n')
  186. print(X2, '\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement