TU Wien:Computernumerik VU (Schranz-Kirlinger)/Übungen SS16/Beispiel 33

Aus VoWi
Zur Navigation springen Zur Suche springen

Lösung[Bearbeiten | Quelltext bearbeiten]

Matlab Code

function Bsp3di

stelle = pi/3;
f = @(x) cos(x); 

%% a) Polynom Grad 1
x = [0 pi/2];
y = [cos(0) cos(pi/2)];

poly = polyfit(x,y,1);
fprintf('a) Polynom: %f %f\n', poly(1),poly(2));
error = f(stelle) - polyval(poly,stelle);
fprintf('a) Fehler: %f\n', error);

%% b) Polynom Grad 2
x = [0 pi/2 pi/4];
y = [cos(0) cos(pi/2) cos(pi/4)];

poly = polyfit(x,y,2);
fprintf('b) Polynom: %f %f %f\n', poly(1),poly(2),poly(3));
error = f(stelle) - polyval(poly,stelle);
fprintf('b) Fehler: %f\n', error);

%% c) Polynom Grad 3
x = [0 pi/2 pi/4 pi/6];
y = [cos(0) cos(pi/2) cos(pi/4) cos(pi/6)];

poly = polyfit(x,y,3);
fprintf('c) Polynom: %f %f %f %f\n', poly(1),poly(2),poly(3),poly(4));
error = f(stelle) - polyval(poly,stelle);
fprintf('c) Fehler: %f\n', error);

%% d) Gerades Polynom Grad 4
x = [0 0 pi/2 0 pi/4];
y = [cos(0) cos(0) cos(pi/2) cos(0) cos(pi/4)];

poly = polyfit(x,y,4);
fprintf('d) Polynom: %f %f %f %f %f\n', poly(1),poly(2),poly(3),poly(4),poly(5));
error = f(stelle) - polyval(poly,stelle);
fprintf('d) Fehler: %f\n', error);

%% e) Ungerades Polynom Grad 3
x = [0 0 0 pi/2];
y = [cos(0) cos(0) cos(0) cos(pi/2)];

poly = polyfit(x,y,3);
fprintf('e) Polynom: %f %f %f %f\n', poly(1),poly(2),poly(3),poly(4));
error = f(stelle) - polyval(poly,stelle);
fprintf('e) Fehler: %f\n', error);

%% f) Taylorpolynom Grad 4 : 1 - x^2/2
%syms x
%res = taylor(cos(x), 'Order', 4);
res =  1- stelle^2 / 2;
fprintf('e) Polynomval: %f \n', res);
error = f(stelle) - res;
fprintf('f) Fehler: %f\n', error);

%% g) Lagrange Polynom x0,x1,x2
x = pi/3;
xi = [0 pi/2 pi/4];
yi = [cos(0) cos(pi/2) cos(pi/4)];
n = size(xi,2);
L = ones(n,size(x,2));
for i=1:n
    for j=1:n
        if (i~=j)
            L(i,:)=L(i,:).*(x-xi(j))/(xi(i)-xi(j));
        end
    end
end
y=0;
for i=1:n
    y=y+yi(i)*L(i,:);
end

fprintf('g) Polynomval: %f \n', y);
error = f(stelle) - y;
fprintf('g) Fehler: %f\n', error);

end