a = 0; b = 1;
g = @(x) 10 * x.^2;
f = @(x) g(x) + 2 * rand(size(x))-1;
n = 9;
x_nodes = linspace(a,b,n+1);
y_nodes = f(x_nodes);

x_values = linspace(0,1,1001);
f_values = f(x_values);
g_values = g(x_values);

Pinterp = polyfit( x_nodes, y_nodes, n );
Pinterp_values = polyval( Pinterp, x_values );

PLeastSquares = polyfit( x_nodes, y_nodes, 2 );
PLeastSquares_values = polyval( PLeastSquares, x_values );

plot( x_values, f_values, '-g', x_values, g_values, '-k', ...
        x_values, Pinterp_values, '-r', x_values, PLeastSquares_values, '-b' )
legend( {'$f(x)$', '$g(x)$', '$\Pi_n f(x)$', '$\tilde{f}_2(x)$'},...
    'Interpreter','latex');

x_values2 = linspace( 0, 2, 1001 );
g_values2 = g(x_values2);
Pinterp_values2 = polyval( Pinterp, x_values2 );
PLeastSquares_values2 = polyval( PLeastSquares, x_values2 );
Pinterp_values2_x2 = Pinterp_values2( end )
%  Pinterp_values2_x2 =
%    -3.3843e+06
PLeastSquares_values2_x2 = PLeastSquares_values2(end)
%  PLeastSquares_values2_x2 =
%     40.2288
plot( x_values, f_values, '-g', x_values2, g_values2, '-k', ...
     x_values2, Pinterp_values2, '-r', x_values2, PLeastSquares_values2, '-b'  )
legend( {'$f(x)$', '$g(x)$', '$\Pi_n f(x)$', '$\tilde f_2(x)$'}, ...
    'Interpreter','latex');