#!/usr/bin/octave


#interpolcaja lagrange'a

#zad 1 znajdz wiel interp dla wezlow w=[-1,0,1,2]
#dla x^3-1 i x^4-2 narysuj wykresy

w=-1:2;
f1=[1 0 0 -1];
f2=[1 0 0 0 -2];
y1=polyval(f1,w);
y2=polyval(f2,w);

p1=polyfit(w,y1,3);
p2=polyfit(w,y2,3);

x=linspace(-1.1,2.1);
#hold on;
plot(x,polyval(f1,x),";f1;",x,polyval(p1,x),";p1;",w,y1,"+")
pause(1);
plot(x,polyval(f2,x),";f2;",x,polyval(p2,x),";p2;",w,y2,"*")
pause(1);
#hold off



#zbieznosc dla sin(x) i wezlow rownoodleglych a czebyszewa
function [e,ew]=testintpL(f=@(x) sin(4*x),a=-1,b=1,NN=[5,10,20,30],rys=3)
#Input:
#f - function handle
#a,b - ends of interval
#NN - array with no of nodes -1
#rys = function plots graphs for N=NN(k) for k <=rys
#
#Call e.g. 
#e=testintpL(f=@(x) sin(4*x),a=-pi,b=2*pi)
 xp=linspace(a,b);
 x=linspace(a,b,10000);
 y=f(x);
 k=1;
 e=zeros(length(NN),2);
 for N=NN,
  wr=linspace(a,b,N+1);
  yr=f(wr);
  pr=polyfit(wr,yr,N);
  
  e(k,1)=norm(y-polyval(pr,x),'inf');
  ew(k,1)=norm(yr-polyval(pr,wr),'inf');
  wc=0.5*(a+b)+0.5*(b-a)*cos(pi*(0.5+(0:N))/(N+1));
  yc=f(wc);
  pc=polyfit(wc,yc,N);
  e(k,2)=norm(y-polyval(pc,x),'inf');
  ew(k,2)=norm(yc-polyval(pc,wc),'inf');
  if(k<=rys)
   plot(xp,polyval(pr,xp),";pr;",xp,polyval(pc,xp),";pc;",xp,f(xp),";f;");
   pause(1);
  endif
  k++;
 endfor
endfunction


a=-pi;b=2*pi;
f=@(x) sin(x);
NN=[5,10,20,30];
[e,ew]=testintpL(f,a,b,NN)

#sin(4x)
f=@(x) sin(4*x)
[e,ew]=testintpL(f,a,b,NN)


#f=log(1+x) on [0,10]
f=@(x) log(1+x);
a=0;b=10;
[e,ew]=testintpL(f,a,b,NN)


#1/(1+x*x) on [-5,5]
f=@(x) 1./(1+x.*x);
a=-5;b=5;
[e,ew]=testintpL(f,a,b,NN)




