%esercizio 1 esame 28.04.22
clear all
close all
clc

a=-2;
b=3;

n1=9;
n2=8;

xx=linspace (a,b);
x1=linspace(a,b,n1);

%nodi di chebishev per minimizzare l'errore

for i=0:n2-1
    x2(i+1)= (a+b)/2 + (b-a)/2*cos((2*i +1)/(2*n2 +2)*pi);
end
f=@(xx) 1./(1 +5*xx.^2);
y1=f(x1);
y2=f(x2);

P1=@(xx) P(x1,y1,xx);
P2=@(xx) P(x2,y2,xx);

fplot(P1,[a,b],'b')
hold on
fplot(P2,[a,b],'r')
fplot(f,[a,b],'g')

plot(x1,y1,'*b')
plot(x2,y2,'*r')

xxi=linspace(-1,3);

g1=@(xxi) abs(f(xxi)-P(x1,y1,xxi));
g2=@(xxi) abs(f(xxi)-P(x2,y2,xxi));

[I1] = TrapezComp(g1,xxi);
[I2] = TrapezComp(g2,xxi);

c=0;
d=1;

x=linspace(c,d);
h=@(x) P1(x) - 10*P2(x) +5;

Nmax=100;
toll=sqrt(eps);
[x0]=secanti(h,c,d,Nmax,toll);

figure
fplot(h,[0,1],'r')
hold on
plot (x0,h(x0), '*b');

function [p] = P(xi,yi,xx)
%Metodo di lagrange

n=length(xi)-1;
p=xx-xx;

for j=0:n
    num=1;
    den=1;
    for i=[1:j-1,j+1:n]
        num=num.*(xx-xi(i+1));
        den=den.*(xi(j+1)-xi(i+1));
    end
    p=p + num./den*yi(j+1);
end
end

function [Ii] = TrapezComp(gi,xxi)
w=ones(size(xxi))*(xxi(2)-xxi(1));
w(1)=w(1)/2;
w(end)=w(end)/2;
G=gi(xxi);
Ii = sqrt(w*G');
end

function [x0]=secanti(h,c,d,Nmax,toll);

x0=c;
x1=d;
r=(h(x0)-h(x1))/(x0-x1);
x1=x0;
x0= x0 - h(x0)/r;
k=1;
e(k)=abs(h(x0));

while k<Nmax && e(k)>toll
    r=(h(x0)-h(x1))/(x0-x1);
    x1=x0;
    x0= x0 - h(x0)/r;
    k=k+1;
    e(k)=abs(h(x0));
end

end