Untitled
unknown
python
2 years ago
1.8 kB
11
Indexable
from math import *
def lagrange_interpolation(x_values, y_values, x):
if len(x_values) != len(y_values):
raise ValueError("Количество точек x и y должно быть одинаковым")
n = len(x_values)
result = 0.0
for i in range(n):
term = y_values[i]
for j in range(n):
if i != j:
term *= (x - x_values[j]) / (x_values[i] - x_values[j])
result += term
return result
def y_val(x):
res = []
for i in x:
res.append(log(tan(i/pi)))
return res
def newton_interpolation(x_values, y_values, x):
if len(x_values) != len(y_values):
raise ValueError("Количество точек x и y должно быть одинаковым")
n = len(x_values)
coefficients = y_values.copy()
for i in range(1, n):
for j in range(n - 1, i - 1, -1):
coefficients[j] = (coefficients[j] - coefficients[j - 1]) / (x_values[j] - x_values[j - i])
result = coefficients[-1]
for i in range(n - 2, -1, -1):
result = result * (x - x_values[i]) + coefficients[i]
return result
# Пример использования:
x_values = [1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7]
y_values = y_val(x_values)
x = 2.5
result_lagrange = lagrange_interpolation(x_values, y_values, x)
result_newton = newton_interpolation(x_values, y_values, x)
print(f"Значение интерполяционного полинома (метод Лагранжа) в точке x={x}: {result_lagrange}")
print(f"Значение интерполяционного полинома (метод Ньютона) в точке x={x}: {result_newton}")
print(f"Значение функции в точке x={x}: {log(tan(x/pi))}")Editor is loading...