Files
TMA4135/exercise2/main.py
2025-09-02 17:51:12 +02:00

56 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from sympy import prod, cos, sin
from sympy.abc import t
from sympy.plotting import plot, plot_parametric
t_i = [0, 0.8976, 1.7952, 2.6928, 3.5904, 4.4880, 5.3856, 6.2832]
x_i = [1, 1.5984, -0.6564, -1.6828, -0.1191, 0.2114, -0.3514, 1]
y_i = [0, 0.7818, 0.9750, 0.4339, -0.4339, -0.975, -0.7818, 0]
n = len(x_i)
def cardinal(x, i, data_x):
return prod([(x - data_x[j]) / (data_x[i] - data_x[j]) for j in range(n) if i != j])
def lagrange_polynomial(x, k, data_x, data_y):
return sum(data_y[i] * cardinal(x, i, data_x) for i in range(k))
n = len(x_i)
domain = (t, t_i[0], t_i[-1])
# a)
x_t = lagrange_polynomial(t, n, t_i, x_i)
plot(
x_t,
domain,
title="x(t) interpolated",
xlabel="t",
ylabel="x",
show=False,
).save("x.png")
# b)
y_t = lagrange_polynomial(t, n, t_i, y_i)
plot(
y_t,
domain,
title="y(t) interpolated",
xlabel="t",
ylabel="y",
show=False,
).save("y.png")
# c) & d)
interpolated = (x_t, y_t)
actual = (cos(t) + sin(2 * t), sin(t))
plot_parametric(
(x_t, y_t, domain, "interpolated"),
(cos(t) + sin(2 * t), sin(t), domain, "actual"),
title="helicopter path - approx. vs actual",
xlabel="x",
ylabel="y",
legend=True,
show=False,
).save("path.png")