function Blatt6_UE3_2
clear; clc;

n = 400;

horner_s = zeros(n,1);
horner_d = zeros(n,1);
sdp_s    = zeros(n,1);
sdp_d    = zeros(n,1);

for g = 1:n
    a = rand(g,1);
    x = rand(1,1); 
    horner_s(g) = horner_single(a, x);
    horner_d(g) = horner(a, x);
    sdp_s(g)    = sdp_single(a, x);
    sdp_d(g)    = sdp(a, x);
end

% HORNER_D als Referenzgroesse
hold off;
plot(1:n, horner_s - horner_d, 'r');
hold on;
plot(1:n, sdp_s    - horner_d, 'b');
plot(1:n, sdp_d    - horner_d, 'k');
legend('horner_s - horner_d', 'sdp_s - horner_d', ...
    'sdp_d - horner_d')

% SDP_D als Referenzgroesse
% plot(1:n, horner_s - sdp_d, 'r');
% plot(1:n, sdp_s    - sdp_d, 'b');
% plot(1:n, horner_d - sdp_d, 'k');
% legend('horner_s - sdp_d', 'sdp_s - sdp_d', ...
%     'horner_d - sdp_d')

disp(['norm(sdp_d    - horner_d, 1) :  ' ...
       num2str(norm(sdp_d - horner_d, 1))]);
disp('..');
disp(['norm(horner_s - horner_d, 1) :  ' ...
       num2str(norm(horner_s - horner_d, 1))]);
disp(['norm(sdp_s    - horner_d, 1) :  ' ...
       num2str(norm(sdp_s - horner_d, 1))]);
disp('..');
disp(['norm(horner_s - sdp_d, 1)    :  ' ...
       num2str(norm(horner_s - sdp_d, 1))]);
disp(['norm(sdp_s    - sdp_d, 1)    :  ' ...
       num2str(norm(sdp_s - sdp_d, 1))]);


hold off
return




% ---------------------------------------
% -------- HORNER -----------------------
% ---------------------------------------
function y = horner(koeff, x)
    n = length(koeff);
    y = koeff(n);
    for k = (n-1):-1:1
        y = x*y + koeff(k);
    end
return

% ---------------------------------------
% -------- HORNER - SINGLE --------------
% ---------------------------------------
function y = horner_single(koeff, x)
    koeff = cast(koeff, 'single');
    x     = cast(x, 'single');
    n = length(koeff);
    y = koeff(n);
    for k = (n-1):-1:1
        y = x*y + koeff(k);
    end
return

% ---------------------------------------
% -------- SUMME DER POTENZEN -----------
% ---------------------------------------
function y = sdp(koeff, x)
    n = length(koeff);
    y = koeff(1);
    for k = 2:n
        y = y + koeff(k)*x^(k-1);
    end
return

% ---------------------------------------
% -------- SUMME DER POTENZEN - SINGLE --
% ---------------------------------------
function y = sdp_single(koeff, x)
    koeff = cast(koeff, 'single');
    n = length(koeff);
    y = koeff(1);
    for k = 2:n
        kp = koeff(k)*pow(x, k-1);
        y  = y + kp;
    end
return

% ---------------------------------------
% -------- POWER FUER SINGLE ------------
% ---------------------------------------
function p = pow(x, k)
    p = single(1);
    for i = 1:k
        p = x*p;
    end
return

