
% Demostration of sensitive dependence to ICs.

set(groot,'defaulttextinterpreter','latex');
set(groot,'defaultAxesTickLabelInterpreter','latex');
set(groot,'defaultLegendInterpreter','latex');
set(groot,'defaultAxesFontSize',14);

format compact
fs=15;
lw=2;

x=0:0.001:1;
%g = inline('2*x');
%g = inline('4.*x.*(1-x)');
g = inline('mod(3*x,1)');


%x0=sqrt(2)/100;
x0=0.012632176524954982
%x0=0.4;
X=[x0];
xo=x0;
Y=[0];

separation=1e-8, Npts=20;
%separation=1e-15, Npts=50;
%separation=0.25

x0near=x0+separation
Xnear=[x0near];
Ynear=[0];
xonear=x0near;

index=[];

for i=1:Npts+1
 index=[index i-1];
 xn=g(xo);   
 X=[X xo xn];
 Y=[Y xn xn];
 xo=xn;
 xnnear=g(xonear);   
 Xnear=[Xnear xonear xnnear];
 Ynear=[Ynear xnnear xnnear];
 xonear=xnnear;

 figure(1);clf;hold on
 set(gca,'DefaultLineLineWidth',lw)
 set(gca,'FontSize',fs)
 plot(x,0*x,'k')
 hold on
 plot(g(x)*0,g(x),'k')
 plot(x,x,'k:')
 plot(x,g(x),'g')
 plot(X,Y,'r')
 plot(Xnear,Ynear,'b')
 axis tight
 xlabel('$x_n$');
 ylabel('$x_{n+1}$');
  
 fprintf('Press any key to continue...\n');
 pause

end

X=X(1:length(X)-1);
Y=Y(1:length(Y)-1);
Xnear=Xnear(1:length(Xnear)-1);
Ynear=Ynear(1:length(Ynear)-1);

figure(1)
clf
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)


plot(x,0*x,'k')
hold on
plot(g(x)*0,g(x),'k')
plot(x,x,'k:')
plot(x,g(x),'g')
plot(X,Y,'r')
plot(Xnear,Ynear,'b')
axis tight
xlabel('$x_n$');
ylabel('$x_{n+1}$');

fprintf('Press any key to continue...\n');
pause

figure(2)
clf
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)

subplot(3,1,1)
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
plot(index,X(1:2:2*Npts+1),'ro-')
%xlabel('$n$');
ylabel('$x_n$');
subplot(3,1,2)
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
plot(index,Xnear(1:2:2*Npts+1),'o-b')
%xlabel('$n$');
ylabel('$x''_n$');
subplot(3,1,3)
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
plot(index,X(1:2:2*Npts+1),'r',index,Xnear(1:2:2*Npts+1),'b')
xlabel('$n$');
ylabel('$x_n ~\&~ x''_n$');


fprintf('Press any key to continue...\n');
pause

figure(3)
clf
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)

subplot(2,1,1)
hold on
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
plot(index,X(1:2:2*Npts+1)-Xnear(1:2:2*Npts+1),'ro-')
%xlabel('$n$');
ylabel('$x_n - x''_n$');

subplot(2,1,2)
%semilogy(index,abs(X(1:2:2*Npts+1)-Xnear(1:2:2*Npts+1)),'ro-','LineWidth',lw)
plot(index,log(abs(X(1:2:2*Npts+1)-Xnear(1:2:2*Npts+1)))./log(10),'ro-','LineWidth',lw)
set(gca,'DefaultLineLineWidth',lw)
set(gca,'FontSize',fs)
axis tight
xlabel('$n$');ylabel('$\log_{10}(|x_n - x''_n|)$');
axis([0 Npts log(separation)./log(10) 1])


