Advertisement
black_duck11

Lagrange interpolation

Oct 19th, 2024 (edited)
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | Science | 0 0
  1. import re
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from tabulate import tabulate
  5. funkcja = input("Podaj funkcję:\nf(x) = ")
  6. lista_x = []
  7. lista_y = []
  8. argument = ''
  9. while argument != '-':
  10.     try:
  11.         argument = input('Podaj x (Wprowadź "-" na końcu): ')
  12.         if argument != '-':
  13.    
  14.             lista_x.append(int(argument))
  15.     except ValueError:
  16.         print('Wprowadź liczbę!')
  17.         continue
  18. temp_funkcja = funkcja.replace('^', '**')
  19. #funkcje dostępne w numpy
  20. funkcje = ['sin', 'cos', 'tan','arcsin', 'arccos', 'arctan', 'sqrt',
  21. 'exp', 'log', 'log10', 'log2']
  22. for f in funkcje:
  23.     temp_funkcja = re.sub(rf'\b{f}\(([^)]+)\)', rf'np.{f}(\1)',
  24. temp_funkcja)
  25. x_values=np.linspace(min(lista_x)-10,max(lista_x)+10)
  26. x_interp = np.linspace(min(lista_x),max(lista_x))
  27. try:
  28.     y_values = [eval(re.sub(r'x', f'({x})', temp_funkcja), {'np':
  29. np}) for x in x_values]
  30.     lista_y = [eval(re.sub(r'x', f'({x})', temp_funkcja), {'np':
  31. np}) for x in lista_x]
  32. except (ValueError, SyntaxError):
  33.     print("OOPs,coś poszło nie tak,s próbuj ponownie")
  34. print('Podana funckja: ',end='')
  35. print(f'f(x) = {funkcja}')
  36. table_data=list(zip(lista_x,lista_y))
  37. headers=['Argumenty','Wartości']
  38. print(tabulate(table_data, headers=headers, tablefmt="grid"))
  39. def interpolacja_lagrange(wartosci_x,wartosci_y):
  40.     n=len(wartosci_x)
  41.  
  42.     wezly=[]
  43.     wielomian=''
  44.     for i in range(n):
  45.  
  46.         skladnik=''
  47.         wspolczynnik=wartosci_y[i]
  48.         if wspolczynnik==0:
  49.             continue
  50.         mianownik=1
  51.  
  52.         for j in range(n):
  53.             if i!=j:
  54.                 mianownik*=(wartosci_x[i] - wartosci_x[j])
  55.                 if wartosci_x[j]>0:
  56.                     skladnik+=f'*(x - {wartosci_x[j]})'
  57.                 elif wartosci_x[j]<0:
  58.                     skladnik+=f'*(x + {abs(wartosci_x[j])})'
  59.                 else:
  60.                     skladnik+=f'*x'
  61.  
  62.         wspolczynnik=f'{wspolczynnik/mianownik}'
  63.         wezly.append(f'{wspolczynnik}{skladnik}')
  64.     wielomian='+'.join(wezly)
  65.     wielomian=wielomian.replace('+-','-')
  66.     return wielomian
  67. wielomian_gotowy=interpolacja_lagrange(lista_x,lista_y)
  68. print('Wielomian interpolacyjny: ',end='')
  69. print(f'L(x) = {wielomian_gotowy}')
  70. y_interp=[eval(re.sub(r'x', f'{x}', wielomian_gotowy), {'np':
  71. np}) for x in x_interp]
  72. plt.plot(x_values, y_values,label=f'f(x)={funkcja}')
  73. plt.plot(x_interp, y_interp, label=f"Wielomian Lagrange'a")
  74. plt.xlabel('x')
  75. plt.ylabel('y')
  76. plt.legend()
  77. plt.grid(True)
  78. plt.scatter(lista_x, lista_y, color='red', label='Wybrane punkty',
  79. marker='o')
  80. plt.title('Wykresy')
  81. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement