Diferencia entre revisiones de «Series de Fourier (Grupo GIXP)»
(→Base trigonométrica compleja) |
|||
| (No se muestran 21 ediciones intermedias de 3 usuarios) | |||
| Línea 15: | Línea 15: | ||
y una función <math> f(x) </math> se descompone como <br /> | y una función <math> f(x) </math> se descompone como <br /> | ||
| − | <math> f(x) \sim \dfrac{d_0}{\sqrt{2T}} + \sum^{\infty}_{n=1} d_n \cdot \cos{\left( \dfrac{n \pi x}{T}\right)} + \sum^{\infty}_{n=1} c_n \cdot \sin{\left( \dfrac{n \pi x}{T}\right)} </math>, <br /><br /> | + | <math> |
| + | f(x) \sim \dfrac{d_0}{\sqrt{2T}} + \sum^{\infty}_{n=1} d_n \cdot \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} + \sum^{\infty}_{n=1} c_n \cdot \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)} | ||
| + | </math>, <br /><br /> | ||
donde <br /> | donde <br /> | ||
* <math> d_0 = \bigl \langle f, \dfrac{1}{\sqrt{2T}} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{2T}} \, dx </math> | * <math> d_0 = \bigl \langle f, \dfrac{1}{\sqrt{2T}} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{2T}} \, dx </math> | ||
| − | * <math> d_n = \bigl \langle f, \cos{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \cos{\left( \dfrac{n \pi x}{T}\right)} \, dx </math> | + | * <math> d_n = \bigl \langle f, \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} \, dx </math> |
| − | * <math> c_n = \bigl \langle f, \sin{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \sin{\left( \dfrac{n \pi x}{T}\right)} \, dx </math>. <br /> <br /> | + | * <math> c_n = \bigl \langle f, \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)} \, dx </math>. <br /> <br /> |
| − | Para hacerlo más ilustrativo, mostremos en una gráfica los 10 primeros términos de la base trigonométrica mencionada para el intervalo [-1,1] | + | Para hacerlo más ilustrativo, mostremos en una gráfica los 10 primeros términos de la base trigonométrica mencionada para el intervalo [-1,1]. |
| − | [[Archivo: | + | [[Archivo:Fourier_BaseTrigonometrica_GIXP.png|400px|thumb|right|Primeros diez términos de la Base Trigonométrica]] |
| − | + | <syntaxhighlight lang="python"> | |
| − | + | ||
| − | + | ||
| − | + | import numpy as np | |
| − | + | from matplotlib import pyplot as plt | |
| + | import seaborn as sns | ||
| − | + | # Definir el intervalo x en [-1,1] | |
| + | x = np.linspace(-1, 1, 500) | ||
| + | |||
| + | # Colores pastel | ||
| + | colors = sns.color_palette("husl", 10) | ||
| + | |||
| + | # ---- 1. Función constante ---- | ||
| + | |||
plt.figure(figsize=(6, 4)) | plt.figure(figsize=(6, 4)) | ||
plt.plot(x, np.full_like(x, 0.5), color=colors[0], linewidth=2, label=r"$\frac{1}{2}$") | plt.plot(x, np.full_like(x, 0.5), color=colors[0], linewidth=2, label=r"$\frac{1}{2}$") | ||
| Línea 41: | Línea 49: | ||
plt.title("Función constante de la base de Fourier") | plt.title("Función constante de la base de Fourier") | ||
plt.legend() | plt.legend() | ||
| + | plt.grid() | ||
plt.show() | plt.show() | ||
| − | + | # ---- 2. Gráfica de los primeros 10 términos de cos(nπx) ---- | |
plt.figure(figsize=(8, 5)) | plt.figure(figsize=(8, 5)) | ||
for n in range(1, 11): | for n in range(1, 11): | ||
| − | |||
plt.plot(x, np.cos(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\cos({n}\pi x)$") | plt.plot(x, np.cos(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\cos({n}\pi x)$") | ||
plt.xlabel("$x$") | plt.xlabel("$x$") | ||
| Línea 52: | Línea 60: | ||
plt.title("Primeros 10 términos de $\cos(n\pi x)$") | plt.title("Primeros 10 términos de $\cos(n\pi x)$") | ||
plt.legend(loc="upper right", fontsize=8) | plt.legend(loc="upper right", fontsize=8) | ||
| + | plt.grid() | ||
plt.show() | plt.show() | ||
| − | + | # ---- 3. Gráfica de los primeros 10 términos de sin(nπx) ---- | |
plt.figure(figsize=(8, 5)) | plt.figure(figsize=(8, 5)) | ||
for n in range(1, 11): | for n in range(1, 11): | ||
| − | |||
plt.plot(x, np.sin(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\sin({n}\pi x)$") | plt.plot(x, np.sin(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\sin({n}\pi x)$") | ||
plt.xlabel("$x$") | plt.xlabel("$x$") | ||
| Línea 63: | Línea 71: | ||
plt.title("Primeros 10 términos de $\sin(n\pi x)$") | plt.title("Primeros 10 términos de $\sin(n\pi x)$") | ||
plt.legend(loc="upper right", fontsize=8) | plt.legend(loc="upper right", fontsize=8) | ||
| + | plt.grid() | ||
plt.show() | plt.show() | ||
| − | |||
| + | </syntaxhighlight> | ||
| + | |||
| + | __TOC__ | ||
=Aproximación de una función continua= | =Aproximación de una función continua= | ||
| − | + | Las series de Fourier también pueden aplicarse sobre intervalos no simétricos, aunque eso conlleva dar una extensión de la función que se busca aproximar de forma par, tal que <math> f(x) = f(-x) </math> o impar, tal que <math> f(x) = - f(-x)</math>. Como ejemplo, aproximaremos la función <math> f(x) = 1 - 2\left| \frac{1}{2} - x \right| </math> definida en el intervalo <math> [0,1] </math>, cuya extensión impar se define como | |
| − | <math> f(x) = 1 - 2\left| \frac{1}{2} - x \right| </math> | + | |
| − | en el intervalo <math> [0,1] </math> | + | |
| − | + | ||
| − | + | ||
<math> | <math> | ||
| − | f | + | f^{*}(x) = |
\begin{cases} | \begin{cases} | ||
f(x), & x \in [0,1] \\ | f(x), & x \in [0,1] \\ | ||
- f(-x), & x \in [-1,0) | - f(-x), & x \in [-1,0) | ||
\end{cases} | \end{cases} | ||
| − | </math> | + | </math> |
| − | + | <br /> | |
| − | + | ||
| − | + | ||
| − | Los coeficientes de la serie de Fourier | + | manteniendo la continuidad de la función en <math> x = 0 </math>. Los coeficientes de la serie de Fourier son |
| − | * <math> d_0 = \bigl \langle f | + | * <math> d_0 = \bigl \langle f^{*}, \dfrac{1}{\sqrt{2}} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \dfrac{1}{\sqrt{2}} \, dx </math> |
| − | * <math> d_n = \bigl \langle f | + | * <math> d_n = \bigl \langle f^{*}, \cos{\left( n \pi x \right)} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \cos{\left( n \pi x \right)} \, dx </math> |
| − | * <math> c_n = \bigl \langle f | + | * <math> c_n = \bigl \langle f^{*}, \sin{\left( n \pi x \right)} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \sin{\left( n \pi x \right)} \, dx </math> |
| + | <br /> | ||
| − | Dado que los coeficientes <math> d_0 </math> y <math> d_n </math> son el resultado de la integral de una función impar <math> f | + | Dado que los coeficientes <math> d_0 </math> y <math> d_n </math> son el resultado de la integral de una función impar <math> f^{*}(x) </math> multiplicada por funciones pares (como la función constante o las funciones asociadas a los cosenos) en un intervalo simétrico, obtenemos que estos términos se anulan, es decir |
<math> | <math> | ||
| − | d_0 = 0, \quad d_n = 0, \quad \forall n \in \mathbb{N} | + | d_0 = 0, \quad d_n = 0, \quad \forall n \in \mathbb{N}. |
</math> | </math> | ||
| Línea 102: | Línea 108: | ||
<math> | <math> | ||
| − | + | f^{*}(x) \sim \sum^{\infty}_{n=1} c_n \cdot \sin{\left( n \pi x \right)}. | |
</math> | </math> | ||
| − | A continuación | + | A continuación, se muestra la suma de los primeros términos de la serie de Fourier de <math> f^{*}(x) </math> junto a esta función para comparar su similitud. Los coeficientes de la serie han sido calculados mediante la fórmula del trapecio con una partición uniforme de malla <math> 10^{-3} </math> del intervalo <math> [-1,1] </math>. |
| − | [[Archivo:GIXP(Aproximación de una función).png|miniaturadeimagen|Aproximación por Fourier de | + | |
| − | {{matlab|codigo= | + | [[Archivo:GIXP(Aproximación de una función).png|miniaturadeimagen|Aproximación por Fourier de <math> f^{*}(x) </math>]] |
| − | % Definición de la función f(x) | + | [[Archivo:GIXP(Errores de la aproximación).png|miniaturadeimagen|Error de la aproximación de <math> f^{*}(x) </math>]] |
| − | f = @(x) 1 - 2*abs(1/2 - x); % Función f(x) en [0,1] | + | |
| + | {{matlab|codigo= | ||
| + | |||
| + | % Definición de la función f(x) y su extensión impar f'(x) | ||
| + | f = @(x) 1 - 2*abs(1/2 - x); % Función original f(x) en [0,1] | ||
fext = @(x) sign(x).*(1 - 2*abs(1/2 - abs(x))); % Extensión impar de f(x) en [-1,1] | fext = @(x) sign(x).*(1 - 2*abs(1/2 - abs(x))); % Extensión impar de f(x) en [-1,1] | ||
| Línea 115: | Línea 125: | ||
a = -1; b = 1; % Extremos del intervalo [-1,1] | a = -1; b = 1; % Extremos del intervalo [-1,1] | ||
h = 1e-3; % Discretización | h = 1e-3; % Discretización | ||
| − | XX = linspace(a, b, (b - a) / h); % Linspace | + | XX = linspace(a, b, (b - a) / h); % Linspace en [-1,1] |
| + | u = linspace(0, 1, 1000); % Puntos para la integración numérica | ||
| − | % Términos de la serie de Fourier | + | % Términos de la serie de Fourier |
| − | + | nn_plot = [1, 5, 10]; % Valores de n para las aproximaciones | |
| + | nn_error = 5:5:50; % Valores de n para los errores | ||
| − | % Colores para cada | + | % Colores para cada n en las gráficas de Fourier |
colors = ['b', 'g', 'r']; | colors = ['b', 'g', 'r']; | ||
| − | % Crear | + | % Crear figura para las aproximaciones de Fourier |
| − | figure('Position', [100, 100, 800, 900]) | + | figure('Position', [100, 100, 800, 900]) |
| − | % | + | % Aproximación de Fourier para nn_plot |
| − | for j = 1:length( | + | for j = 1:length(nn_plot) |
| − | n = | + | n = nn_plot(j); % Número de términos de la serie |
s = zeros(1, length(XX)); % Inicializar la serie de Fourier | s = zeros(1, length(XX)); % Inicializar la serie de Fourier | ||
% Cálculo de los coeficientes de Fourier | % Cálculo de los coeficientes de Fourier | ||
for k = 1:n | for k = 1:n | ||
| − | % | + | % Aproximación de la integral usando la regla del trapecio |
| − | + | w = ones(size(u)); | |
| − | w = ones(size(u)); | + | w(1) = 1/2; w(end) = 1/2; |
| − | w(1) = 1/2; w(end) = 1/2; | + | |
| − | % | + | % Producto f(x) * sin(k*pi*x) |
| − | + | integrand = f(u) .* sin(k * pi * u); | |
ak = 2 * trapz(u, integrand .* w); % Coeficiente de Fourier a_k | ak = 2 * trapz(u, integrand .* w); % Coeficiente de Fourier a_k | ||
% Sumar el término de la serie | % Sumar el término de la serie | ||
| − | s = s + ak * sin(k * pi * XX); | + | s = s + ak * sin(k * pi * XX); |
end | end | ||
| − | % Crear subgráficas para cada n | + | % Crear subgráficas para cada n |
subplot(3, 1, j) | subplot(3, 1, j) | ||
hold on; grid on; | hold on; grid on; | ||
plot(XX, fext(XX), 'k', 'LineWidth', 2) % Función extendida en negro | plot(XX, fext(XX), 'k', 'LineWidth', 2) % Función extendida en negro | ||
| − | plot(XX, s, colors(j), 'LineWidth', 2) | + | plot(XX, s, colors(j), 'LineWidth', 2) % Serie de Fourier aproximada |
title(['Aproximación de Fourier con n = ', num2str(n)], 'FontSize', 16) | title(['Aproximación de Fourier con n = ', num2str(n)], 'FontSize', 16) | ||
| − | % Leyenda | + | % Leyenda |
legend('Extensión impar de f(x)', 'Serie de Fourier de f(x)', 'Location', 'southeast', 'FontSize', 10) | legend('Extensión impar de f(x)', 'Serie de Fourier de f(x)', 'Location', 'southeast', 'FontSize', 10) | ||
| − | |||
xlabel('x', 'FontSize', 14) | xlabel('x', 'FontSize', 14) | ||
ylabel('f(x) y Serie de Fourier', 'FontSize', 14) | ylabel('f(x) y Serie de Fourier', 'FontSize', 14) | ||
end | end | ||
| + | |||
| + | % Inicializar vectores para almacenar los errores | ||
| + | errors_L2 = zeros(1, length(nn_error)); | ||
| + | errors_inf = zeros(1, length(nn_error)); | ||
| + | |||
| + | % Crear figura para los errores | ||
| + | figure('Position', [100, 100, 800, 600]) | ||
| + | |||
| + | % Calcular errores para cada n en nn_error | ||
| + | for j = 1:length(nn_error) | ||
| + | n = nn_error(j); | ||
| + | s = zeros(1, length(XX)); | ||
| + | |||
| + | % Cálculo de la serie de Fourier | ||
| + | for k = 1:n | ||
| + | w = ones(size(u)); | ||
| + | w(1) = 1/2; w(end) = 1/2; | ||
| + | |||
| + | % Producto f(x) * sin(k*pi*x) | ||
| + | integrand = f(u) .* sin(k * pi * u); | ||
| + | ak = 2 * trapz(u, integrand .* w); | ||
| + | |||
| + | % Sumar el término de la serie | ||
| + | s = s + ak * sin(k * pi * XX); | ||
| + | end | ||
| + | |||
| + | % Calcular errores | ||
| + | errors_L2(j) = sqrt(trapz(XX, (fext(XX) - s).^2)); | ||
| + | errors_inf(j) = max(abs(fext(XX) - s)); | ||
| + | end | ||
| + | |||
| + | % Graficar errores | ||
| + | subplot(2, 1, 1) | ||
| + | plot(nn_error, errors_L2, 'bo-', 'LineWidth', 2) | ||
| + | title('Error L2 en función de n', 'FontSize', 16) | ||
| + | xlabel('Número de términos n', 'FontSize', 14) | ||
| + | ylabel('Error L2', 'FontSize', 14) | ||
| + | grid on | ||
| + | |||
| + | subplot(2, 1, 2) | ||
| + | plot(nn_error, errors_inf, 'ro-', 'LineWidth', 2) | ||
| + | title('Error uniforme en función de n', 'FontSize', 16) | ||
| + | xlabel('Número de términos n', 'FontSize', 14) | ||
| + | ylabel('Error uniforme', 'FontSize', 14) | ||
| + | grid on | ||
| + | |||
}} | }} | ||
| − | |||
| + | |||
| + | También hemos calculado el error en norma \( L^2 \) y en norma uniforme para distintas \( n \) y así hacernos una idea de la función que siguen los errores de este método en función de \( n \). | ||
| + | |||
| + | Hemos estimado que siguen la función \( e^{-\alpha n} \), con \( \alpha > 1 \). | ||
=Base trigonométrica compleja= | =Base trigonométrica compleja= | ||
| Línea 168: | Línea 227: | ||
Se puede definir el conjunto de funciones que toman valores complejos y cuyo modulo al cuadrado es integrable. | Se puede definir el conjunto de funciones que toman valores complejos y cuyo modulo al cuadrado es integrable. | ||
| − | <math> L^2( \Omega ) = \left\{ f: \mathbb{R} \to \mathbb{C} \ | + | <math> L^2( \Omega ) = \left\{ f: \mathbb{R} \to \mathbb{C} \ : \ \int_{\Omega} \left| f(x) \right|^2 \, dx < \infty \right\} </math>. |
| − | Este conjunto tiene estructura de espacio vectorial y admite un producto escalar <math> \bigl \langle f, g \bigr \rangle_{\Omega} = \int_{\Omega} f(z) \overline{g(z)} \, dx </math> | + | Este conjunto tiene estructura de espacio vectorial y admite un producto escalar <math> \bigl \langle f, g \bigr \rangle_{\Omega} = \int_{\Omega} f(z) \overline{g(z)} \, dx </math> dotándole de una estructura de espacio de Hilbert. |
| − | En esta sección se | + | En esta sección, se desarrollará una serie de Fourier para aproximar la función |
| − | <math> f(x) = 4x \left( \frac{1}{2} - x \right)^2 + ix </math> | + | <math> f(x) = 4x \left( \frac{1}{2} - x \right)^2 + ix </math>, |
| − | definida en el intervalo <math> [0,1] </math> | + | que toma valores complejos, definida en el intervalo <math> [0,1] </math>. |
| − | El objetivo es expresar la función como combinación lineal de elementos de una base del espacio | + | El objetivo es expresar la función como combinación lineal de elementos de una base del espacio, en particular, la base trigonométrica. Esta base para <math> L^2([-\pi,\pi]) </math> es |
| − | + | <math> B_{L^2([-\pi,\pi])} = \left\{\frac{1}{\sqrt{2\pi}}e^{ikx}\right\}_{k \in \mathbb{Z}} </math>. | |
| − | * <math> z_k = \bigl \langle f, e^{2\pi ikx} \bigr \rangle_{L^2} = \int_{0}^{1} f(x) \cdot e^{2\pi ikx} \, dx, \quad \forall k \in \mathbb{Z} </math> | + | Aplicando el cambio de variable |
| + | |||
| + | <math> x = \frac{\log \left(\sqrt{\frac{2\pi}{b-a}} \right)}{ik} + \frac{2\pi}{b-a}(y-a) </math>, | ||
| + | |||
| + | trasladamos la base al intervalo <math> \left[a,b\right] </math>: | ||
| + | |||
| + | <math> B_{L^2([a,b])} = \left\{\frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(y-a)}\right\}_{k \in \mathbb{Z}} </math> | ||
| + | |||
| + | En efecto, es base, ya que | ||
| + | |||
| + | * <math> \bigl \langle \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)}, \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \bigr \rangle_{L^2([a,b])} = \int_{a}^{b} \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \frac{1}{\sqrt{b-a}}e^{-ik\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{b-a}\int_{a}^{b} \, dx = 1 </math> | ||
| + | |||
| + | * <math> \bigl \langle \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)}, \frac{1}{\sqrt{b-a}}e^{ih\frac{2\pi}{b-a}(x-a)} \bigr \rangle_{L^2([a,b])} = \int_{a}^{b} \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \frac{1}{\sqrt{b-a}}e^{-ih\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{b-a}\int_{a}^{b} e^{i(k-h)\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{i(k-h)2\pi} \left( 1 - 1 \right) \, dx = 0 </math> | ||
| + | |||
| + | Escogiendo el intervalo <math> \left[ 0,1 \right] </math>, se tiene que la base trigonométrica compleja de <math> L^2([0,1]) </math> es | ||
| + | |||
| + | <math> B_{L^2([0,1])} = \left\{e^{2\pi ikx}\right\}_{k \in \mathbb{Z}} </math>, | ||
| + | <br /> | ||
| + | |||
| + | y será la que se usará para desarrollar la serie de Fourier. | ||
| + | |||
| + | Los coeficientes de la serie se calculan de la siguiente manera: | ||
| + | |||
| + | * <math> z_k = \bigl \langle f, e^{2\pi ikx} \bigr \rangle_{L^2([0,1])} = \int_{0}^{1} f(x) \cdot e^{-2\pi ikx} \, dx, \quad \forall k \in \mathbb{Z} </math> | ||
Por lo tanto, la serie de Fourier queda expresada únicamente en términos de exponenciales complejas: | Por lo tanto, la serie de Fourier queda expresada únicamente en términos de exponenciales complejas: | ||
| Línea 189: | Línea 271: | ||
f(x) \sim \sum^{+\infty}_{k=-\infty} z_k \cdot e^{2\pi ikx} | f(x) \sim \sum^{+\infty}_{k=-\infty} z_k \cdot e^{2\pi ikx} | ||
</math> | </math> | ||
| + | |||
| + | [[Archivo:Fourier_Real_GIXP.png|400px|thumb|right|Serie de Fourier compleja de <math> f(x) </math>. Parte real.]] | ||
| + | [[Archivo:Fourier_Imaginaria_GIXP.png|400px|thumb|right|Serie de Fourier compleja de <math> f(x) </math>. Parte imaginaria.]] | ||
| + | |||
| + | <syntaxhighlight lang="python"> | ||
| + | |||
| + | import numpy as np | ||
| + | import matplotlib.pyplot as plt | ||
| + | from scipy.integrate import quad | ||
| + | |||
| + | # Definir la función a aproximar | ||
| + | |||
| + | def f(x): | ||
| + | return 4*x*(0.5 - x)**2 + 1j*x | ||
| + | |||
| + | # Calcular coeficientes de Fourier en la base {e^(i 2πnx)} | ||
| + | |||
| + | def fourier_coefficient(n): | ||
| + | |||
| + | integrand = lambda x: f(x) * np.exp(-1j * 2 * np.pi * n * x) | ||
| + | |||
| + | real_part, _ = quad(lambda x: integrand(x).real, 0, 1) | ||
| + | imag_part, _ = quad(lambda x: integrand(x).imag, 0, 1) | ||
| + | |||
| + | return real_part + 1j * imag_part # Devolver coeficiente complejo | ||
| + | |||
| + | # Aproximar la función con los primeros N términos | ||
| + | |||
| + | def fourier_approx_real(x, N): | ||
| + | S_N = sum(fourier_coefficient(n) * np.exp(1j * 2 * np.pi * n * x) for n in range(-N, N+1)) | ||
| + | return S_N.real # Tomamos la parte real de la serie de Fourier | ||
| + | |||
| + | def fourier_approx_imag(x, N): | ||
| + | S_N = sum(fourier_coefficient(n) * np.exp(1j * 2 * np.pi * n * x) for n in range(-N, N+1)) | ||
| + | return S_N.imag # Tomamos la parte imaginaria de la serie de Fourier | ||
| + | |||
| + | # Valores de x para la gráfica | ||
| + | |||
| + | x_vals = np.linspace(0, 1, 500) | ||
| + | f_real_vals = np.array([f(x).real for x in x_vals]) | ||
| + | f_imag_vals = np.array([f(x).imag for x in x_vals]) | ||
| + | |||
| + | # Aproximaciones con distintos N | ||
| + | |||
| + | N_values = [5, 10, 20] | ||
| + | |||
| + | # Parte Real | ||
| + | |||
| + | plt.figure(figsize=(10, 6)) | ||
| + | plt.plot(x_vals, f_real_vals, label='Función Original', linewidth=2, color='black') | ||
| + | |||
| + | for N in N_values: | ||
| + | approx_vals = np.array([fourier_approx_real(x, N) for x in x_vals]) | ||
| + | plt.plot(x_vals, approx_vals, label=f'Aproximación con {N} términos') | ||
| + | |||
| + | plt.xlabel('x') | ||
| + | plt.ylabel('Re f(x)') | ||
| + | plt.title('Aproximación de Fourier de f(x) - Parte real') | ||
| + | plt.legend() | ||
| + | plt.grid() | ||
| + | plt.show() | ||
| + | |||
| + | # Parte Imaginaria | ||
| + | |||
| + | plt.figure(figsize=(10, 6)) | ||
| + | plt.plot(x_vals, f_imag_vals, label='Función Original', linewidth=2, color='black') | ||
| + | |||
| + | for N in N_values: | ||
| + | approx_vals = np.array([fourier_approx_imag(x, N) for x in x_vals]) | ||
| + | plt.plot(x_vals, approx_vals, label=f'Aproximación con {N} términos') | ||
| + | |||
| + | plt.xlabel('x') | ||
| + | plt.ylabel('Im f(x)') | ||
| + | plt.title('Aproximación de Fourier de f(x) - Parte imaginaria') | ||
| + | plt.legend() | ||
| + | plt.grid() | ||
| + | plt.show() | ||
| + | |||
| + | |||
| + | </syntaxhighlight> | ||
| + | |||
| + | = Bibliografía = | ||
| + | |||
| + | * [https://es.wikipedia.org/wiki/Serie_de_Fourier Wikipedia. Series de Fourier. Editada por última vez el 12/09/2024] | ||
[[Categoría:EDP]] | [[Categoría:EDP]] | ||
[[Categoría:EDP24/25]] | [[Categoría:EDP24/25]] | ||
Revisión actual del 23:56 19 feb 2025
| Trabajo realizado por estudiantes | |
|---|---|
| Título | Series de Fourier. Grupo GIXP |
| Asignatura | EDP |
| Curso | 2024-25 |
| Autores | Gonzalo Garelly
Israel López Francisco Lavao Paula León |
| Este artículo ha sido escrito por estudiantes como parte de su evaluación en la asignatura | |
Una serie de Fourier (en honor al matemático Jean-Baptiste Joseph Fourier) consta de una suma infinita de funciones sinusoidales definidas en un dominio [math] \Omega \subseteq \mathbb{R}^n [/math] que convergen en mínimos cuadrados a una cierta función [math] f(x) [/math]. En el ámbito del análisis funcional, las series de Fourier son una poderosa herramienta capaz de descomponer cualquier función periódica definida sobre un cierto dominio como una combinación lineal de infinitas funciones sinusoidales. Poseen numerosas aplicaciones en física e ingeniería, relacionadas con el procesamiento de señales acústicas, análisis vibratorio y compresión de datos, entre otras.
En el espacio de Hilbert [math] L^2([-T,T]) = \{f : [-T,T] \rightarrow \mathbb{R} : \int_{-T}^{T} |f(x)|^2 \, dx \lt \infty\} [/math] se define un producto escalar [math] \langle f_1, f_2 \rangle = \int_{-T}^{T} f(x) \cdot g(x) \, dx[/math], las funciones sinusoidales forman una base ortonormal
[math] B = \Biggl\{ \dfrac{1}{\sqrt{2T}}\Biggr\} \cup \Biggl\{ \dfrac{1}{\sqrt{T}} \cdot \cos{\left( \dfrac{n \pi x}{T}\right)} \Biggr\}_{n \in \mathbb{N}} \cup \Biggl\{ \dfrac{1}{\sqrt{T}} \cdot \sin{\left( \dfrac{n \pi x}{T}\right)} \Biggr\}_{n \in \mathbb{N}} [/math],
y una función [math] f(x) [/math] se descompone como
[math]
f(x) \sim \dfrac{d_0}{\sqrt{2T}} + \sum^{\infty}_{n=1} d_n \cdot \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} + \sum^{\infty}_{n=1} c_n \cdot \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)}
[/math],
donde
- [math] d_0 = \bigl \langle f, \dfrac{1}{\sqrt{2T}} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{2T}} \, dx [/math]
- [math] d_n = \bigl \langle f, \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{T}} \cos{\left( \dfrac{n \pi x}{T}\right)} \, dx [/math]
- [math] c_n = \bigl \langle f, \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)} \bigr \rangle = \int_{-T}^{T} f(x) \cdot \dfrac{1}{\sqrt{T}} \sin{\left( \dfrac{n \pi x}{T}\right)} \, dx [/math].
Para hacerlo más ilustrativo, mostremos en una gráfica los 10 primeros términos de la base trigonométrica mencionada para el intervalo [-1,1].
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
# Definir el intervalo x en [-1,1]
x = np.linspace(-1, 1, 500)
# Colores pastel
colors = sns.color_palette("husl", 10)
# ---- 1. Función constante ----
plt.figure(figsize=(6, 4))
plt.plot(x, np.full_like(x, 0.5), color=colors[0], linewidth=2, label=r"$\frac{1}{2}$")
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
plt.title("Función constante de la base de Fourier")
plt.legend()
plt.grid()
plt.show()
# ---- 2. Gráfica de los primeros 10 términos de cos(nπx) ----
plt.figure(figsize=(8, 5))
for n in range(1, 11):
plt.plot(x, np.cos(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\cos({n}\pi x)$")
plt.xlabel("$x$")
plt.ylabel("$\cos(n\pi x)$")
plt.title("Primeros 10 términos de $\cos(n\pi x)$")
plt.legend(loc="upper right", fontsize=8)
plt.grid()
plt.show()
# ---- 3. Gráfica de los primeros 10 términos de sin(nπx) ----
plt.figure(figsize=(8, 5))
for n in range(1, 11):
plt.plot(x, np.sin(n * np.pi * x), color=colors[n-1], linewidth=2, label=rf"$\sin({n}\pi x)$")
plt.xlabel("$x$")
plt.ylabel("$\sin(n\pi x)$")
plt.title("Primeros 10 términos de $\sin(n\pi x)$")
plt.legend(loc="upper right", fontsize=8)
plt.grid()
plt.show()1 Aproximación de una función continua
Las series de Fourier también pueden aplicarse sobre intervalos no simétricos, aunque eso conlleva dar una extensión de la función que se busca aproximar de forma par, tal que [math] f(x) = f(-x) [/math] o impar, tal que [math] f(x) = - f(-x)[/math]. Como ejemplo, aproximaremos la función [math] f(x) = 1 - 2\left| \frac{1}{2} - x \right| [/math] definida en el intervalo [math] [0,1] [/math], cuya extensión impar se define como
[math]
f^{*}(x) =
\begin{cases}
f(x), & x \in [0,1] \\
- f(-x), & x \in [-1,0)
\end{cases}
[/math]
manteniendo la continuidad de la función en [math] x = 0 [/math]. Los coeficientes de la serie de Fourier son
- [math] d_0 = \bigl \langle f^{*}, \dfrac{1}{\sqrt{2}} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \dfrac{1}{\sqrt{2}} \, dx [/math]
- [math] d_n = \bigl \langle f^{*}, \cos{\left( n \pi x \right)} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \cos{\left( n \pi x \right)} \, dx [/math]
- [math] c_n = \bigl \langle f^{*}, \sin{\left( n \pi x \right)} \bigr \rangle = \int_{-1}^{1} f^{*}(x) \cdot \sin{\left( n \pi x \right)} \, dx [/math]
Dado que los coeficientes [math] d_0 [/math] y [math] d_n [/math] son el resultado de la integral de una función impar [math] f^{*}(x) [/math] multiplicada por funciones pares (como la función constante o las funciones asociadas a los cosenos) en un intervalo simétrico, obtenemos que estos términos se anulan, es decir
[math] d_0 = 0, \quad d_n = 0, \quad \forall n \in \mathbb{N}. [/math]
Por lo tanto, la serie de Fourier queda expresada únicamente en términos de senos:
[math] f^{*}(x) \sim \sum^{\infty}_{n=1} c_n \cdot \sin{\left( n \pi x \right)}. [/math]
A continuación, se muestra la suma de los primeros términos de la serie de Fourier de [math] f^{*}(x) [/math] junto a esta función para comparar su similitud. Los coeficientes de la serie han sido calculados mediante la fórmula del trapecio con una partición uniforme de malla [math] 10^{-3} [/math] del intervalo [math] [-1,1] [/math].
% Definición de la función f(x) y su extensión impar f'(x)
f = @(x) 1 - 2*abs(1/2 - x); % Función original f(x) en [0,1]
fext = @(x) sign(x).*(1 - 2*abs(1/2 - abs(x))); % Extensión impar de f(x) en [-1,1]
% Intervalo y parámetros
a = -1; b = 1; % Extremos del intervalo [-1,1]
h = 1e-3; % Discretización
XX = linspace(a, b, (b - a) / h); % Linspace en [-1,1]
u = linspace(0, 1, 1000); % Puntos para la integración numérica
% Términos de la serie de Fourier
nn_plot = [1, 5, 10]; % Valores de n para las aproximaciones
nn_error = 5:5:50; % Valores de n para los errores
% Colores para cada n en las gráficas de Fourier
colors = ['b', 'g', 'r'];
% Crear figura para las aproximaciones de Fourier
figure('Position', [100, 100, 800, 900])
% Aproximación de Fourier para nn_plot
for j = 1:length(nn_plot)
n = nn_plot(j); % Número de términos de la serie
s = zeros(1, length(XX)); % Inicializar la serie de Fourier
% Cálculo de los coeficientes de Fourier
for k = 1:n
% Aproximación de la integral usando la regla del trapecio
w = ones(size(u));
w(1) = 1/2; w(end) = 1/2;
% Producto f(x) * sin(k*pi*x)
integrand = f(u) .* sin(k * pi * u);
ak = 2 * trapz(u, integrand .* w); % Coeficiente de Fourier a_k
% Sumar el término de la serie
s = s + ak * sin(k * pi * XX);
end
% Crear subgráficas para cada n
subplot(3, 1, j)
hold on; grid on;
plot(XX, fext(XX), 'k', 'LineWidth', 2) % Función extendida en negro
plot(XX, s, colors(j), 'LineWidth', 2) % Serie de Fourier aproximada
title(['Aproximación de Fourier con n = ', num2str(n)], 'FontSize', 16)
% Leyenda
legend('Extensión impar de f(x)', 'Serie de Fourier de f(x)', 'Location', 'southeast', 'FontSize', 10)
xlabel('x', 'FontSize', 14)
ylabel('f(x) y Serie de Fourier', 'FontSize', 14)
end
% Inicializar vectores para almacenar los errores
errors_L2 = zeros(1, length(nn_error));
errors_inf = zeros(1, length(nn_error));
% Crear figura para los errores
figure('Position', [100, 100, 800, 600])
% Calcular errores para cada n en nn_error
for j = 1:length(nn_error)
n = nn_error(j);
s = zeros(1, length(XX));
% Cálculo de la serie de Fourier
for k = 1:n
w = ones(size(u));
w(1) = 1/2; w(end) = 1/2;
% Producto f(x) * sin(k*pi*x)
integrand = f(u) .* sin(k * pi * u);
ak = 2 * trapz(u, integrand .* w);
% Sumar el término de la serie
s = s + ak * sin(k * pi * XX);
end
% Calcular errores
errors_L2(j) = sqrt(trapz(XX, (fext(XX) - s).^2));
errors_inf(j) = max(abs(fext(XX) - s));
end
% Graficar errores
subplot(2, 1, 1)
plot(nn_error, errors_L2, 'bo-', 'LineWidth', 2)
title('Error L2 en función de n', 'FontSize', 16)
xlabel('Número de términos n', 'FontSize', 14)
ylabel('Error L2', 'FontSize', 14)
grid on
subplot(2, 1, 2)
plot(nn_error, errors_inf, 'ro-', 'LineWidth', 2)
title('Error uniforme en función de n', 'FontSize', 16)
xlabel('Número de términos n', 'FontSize', 14)
ylabel('Error uniforme', 'FontSize', 14)
grid on
También hemos calculado el error en norma \( L^2 \) y en norma uniforme para distintas \( n \) y así hacernos una idea de la función que siguen los errores de este método en función de \( n \).
Hemos estimado que siguen la función \( e^{-\alpha n} \), con \( \alpha > 1 \).
2 Base trigonométrica compleja
Se puede definir el conjunto de funciones que toman valores complejos y cuyo modulo al cuadrado es integrable.
[math] L^2( \Omega ) = \left\{ f: \mathbb{R} \to \mathbb{C} \ : \ \int_{\Omega} \left| f(x) \right|^2 \, dx \lt \infty \right\} [/math].
Este conjunto tiene estructura de espacio vectorial y admite un producto escalar [math] \bigl \langle f, g \bigr \rangle_{\Omega} = \int_{\Omega} f(z) \overline{g(z)} \, dx [/math] dotándole de una estructura de espacio de Hilbert.
En esta sección, se desarrollará una serie de Fourier para aproximar la función
[math] f(x) = 4x \left( \frac{1}{2} - x \right)^2 + ix [/math],
que toma valores complejos, definida en el intervalo [math] [0,1] [/math].
El objetivo es expresar la función como combinación lineal de elementos de una base del espacio, en particular, la base trigonométrica. Esta base para [math] L^2([-\pi,\pi]) [/math] es
[math] B_{L^2([-\pi,\pi])} = \left\{\frac{1}{\sqrt{2\pi}}e^{ikx}\right\}_{k \in \mathbb{Z}} [/math].
Aplicando el cambio de variable
[math] x = \frac{\log \left(\sqrt{\frac{2\pi}{b-a}} \right)}{ik} + \frac{2\pi}{b-a}(y-a) [/math],
trasladamos la base al intervalo [math] \left[a,b\right] [/math]:
[math] B_{L^2([a,b])} = \left\{\frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(y-a)}\right\}_{k \in \mathbb{Z}} [/math]
En efecto, es base, ya que
- [math] \bigl \langle \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)}, \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \bigr \rangle_{L^2([a,b])} = \int_{a}^{b} \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \frac{1}{\sqrt{b-a}}e^{-ik\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{b-a}\int_{a}^{b} \, dx = 1 [/math]
- [math] \bigl \langle \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)}, \frac{1}{\sqrt{b-a}}e^{ih\frac{2\pi}{b-a}(x-a)} \bigr \rangle_{L^2([a,b])} = \int_{a}^{b} \frac{1}{\sqrt{b-a}}e^{ik\frac{2\pi}{b-a}(x-a)} \frac{1}{\sqrt{b-a}}e^{-ih\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{b-a}\int_{a}^{b} e^{i(k-h)\frac{2\pi}{b-a}(x-a)} \, dx = \frac{1}{i(k-h)2\pi} \left( 1 - 1 \right) \, dx = 0 [/math]
Escogiendo el intervalo [math] \left[ 0,1 \right] [/math], se tiene que la base trigonométrica compleja de [math] L^2([0,1]) [/math] es
[math] B_{L^2([0,1])} = \left\{e^{2\pi ikx}\right\}_{k \in \mathbb{Z}} [/math],
y será la que se usará para desarrollar la serie de Fourier.
Los coeficientes de la serie se calculan de la siguiente manera:
- [math] z_k = \bigl \langle f, e^{2\pi ikx} \bigr \rangle_{L^2([0,1])} = \int_{0}^{1} f(x) \cdot e^{-2\pi ikx} \, dx, \quad \forall k \in \mathbb{Z} [/math]
Por lo tanto, la serie de Fourier queda expresada únicamente en términos de exponenciales complejas:
[math] f(x) \sim \sum^{+\infty}_{k=-\infty} z_k \cdot e^{2\pi ikx} [/math]
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
# Definir la función a aproximar
def f(x):
return 4*x*(0.5 - x)**2 + 1j*x
# Calcular coeficientes de Fourier en la base {e^(i 2πnx)}
def fourier_coefficient(n):
integrand = lambda x: f(x) * np.exp(-1j * 2 * np.pi * n * x)
real_part, _ = quad(lambda x: integrand(x).real, 0, 1)
imag_part, _ = quad(lambda x: integrand(x).imag, 0, 1)
return real_part + 1j * imag_part # Devolver coeficiente complejo
# Aproximar la función con los primeros N términos
def fourier_approx_real(x, N):
S_N = sum(fourier_coefficient(n) * np.exp(1j * 2 * np.pi * n * x) for n in range(-N, N+1))
return S_N.real # Tomamos la parte real de la serie de Fourier
def fourier_approx_imag(x, N):
S_N = sum(fourier_coefficient(n) * np.exp(1j * 2 * np.pi * n * x) for n in range(-N, N+1))
return S_N.imag # Tomamos la parte imaginaria de la serie de Fourier
# Valores de x para la gráfica
x_vals = np.linspace(0, 1, 500)
f_real_vals = np.array([f(x).real for x in x_vals])
f_imag_vals = np.array([f(x).imag for x in x_vals])
# Aproximaciones con distintos N
N_values = [5, 10, 20]
# Parte Real
plt.figure(figsize=(10, 6))
plt.plot(x_vals, f_real_vals, label='Función Original', linewidth=2, color='black')
for N in N_values:
approx_vals = np.array([fourier_approx_real(x, N) for x in x_vals])
plt.plot(x_vals, approx_vals, label=f'Aproximación con {N} términos')
plt.xlabel('x')
plt.ylabel('Re f(x)')
plt.title('Aproximación de Fourier de f(x) - Parte real')
plt.legend()
plt.grid()
plt.show()
# Parte Imaginaria
plt.figure(figsize=(10, 6))
plt.plot(x_vals, f_imag_vals, label='Función Original', linewidth=2, color='black')
for N in N_values:
approx_vals = np.array([fourier_approx_imag(x, N) for x in x_vals])
plt.plot(x_vals, approx_vals, label=f'Aproximación con {N} términos')
plt.xlabel('x')
plt.ylabel('Im f(x)')
plt.title('Aproximación de Fourier de f(x) - Parte imaginaria')
plt.legend()
plt.grid()
plt.show()