Vamos substituir a tabela $T$ por uma função $f:[a,b]\to \mathbb{R}$ e tomar uma família de funções $\mathbf{F}=\{ f_1, \dots f_n\}$, todas definidas no intervalo $[a,b]$. E considerar o problema de encontrar os coeficientes $a_1,\dots,a_n$ que minimize o
resíduo quadrático $\text{Res}(f,a_1,\dots,a_n) = \int_a^b(\sum a_if_i(x) -f(x))^2 dx$.
De modo parecido ao caso discreto resolvemos este problema ao solucionar o sistema normal associado:
$$ Ax=b$$
onde as componentes da matriz de coeficientes são:
$$ \begin{gather} a_{ij} = \langle f_i, f_j \rangle = \int_a^b f_i(x)f_j(x)dx\\
b_i = \langle f , f_i \rangle = \int_a^b f_i(x)f_j(x)dx \end{gather} $$
Achar uma aproximação de $f(x) = \sin(x)$ por um polinômio menor ou igual a três no intervalo $[-\pi,\pi]$.
#Uma boa oportunidade para usar o sympy!
import sympy as sp
from sympy.interactive import printing
printing.init_printing()
x, y, z = sp.symbols("x y z")
f, g, h = map(sp.Function, 'fgh')
f1 = map(sp.Function, 'f1')
f2 = map(sp.Function, 'f2')
f3 = map(sp.Function, 'f3')
f4 = map(sp.Function, 'f4')
f = sp.sin(x)
f1 = 1
f2 = x
f3= x**2
f4= x**3
def escalar(f,g):
''' produto de duas funções entre -Pi e Pi '''
return sp.integrate(f*g,(x,-sp.pi,sp.pi))
sp.integrate(f1*f3,(x,0,1))
escalar(f1,f1)
escalar(f1,f2)
escalar(f1,f3)
escalar(f1,f4)
escalar(f2,f2)
escalar(f2,f3)
escalar(f2,f4)
escalar(f3,f3)
escalar(f3,f4)
escalar(f4,f4)
escalar(f,f1)
escalar(f,f2)
escalar(f,f3)
escalar(f,f4)
F = [f1,f2,f3,f4]
A1 = [escalar(f1,g) for g in F]
A2 = [escalar(f2,g) for g in F]
A3 = [escalar(f3,g) for g in F]
A4 = [escalar(f4,g) for g in F]
A = sp.Matrix([A1,A2,A3,A4])
A
b=sp.Matrix([escalar(f,g) for g in F])
b
a = A**(-1)*b
a
sp.N(a[1])
sp.N(a[3])
g = a[1]*x + a[3]*x**3
g
h=f.series(x, 0,4).removeO()
h
import numpy
t=numpy.linspace(-3,3,100)
fl=sp.lambdify(x,f,"numpy")
gl = sp.lambdify(x,g,"numpy")
hl = sp.lambdify(x,h, "numpy")
%matplotlib inline
from matplotlib.pyplot import plot,grid
plot(t,fl(t),t,gl(t))
grid()
plot(t,fl(t),t,hl(t))
grid()