
%lab5.m solving nonlienar equations
graphics_toolkit("gnuplot");

%1 slve some simple equations using fzero and fsolve

x=fzero(@(x) x*x-2,[1,2])
x-sqrt(2)


[x,fval,info,output]=fzero(@(x) x*x-2,2)
x-sqrt(2)


x=fzero(@(x) x*x-2,1)
x-sqrt(2)


x=fzero(@(x) x*x-2,0)
x-sqrt(2)

%the next line si commented out since it give an error so the script breaks
%x=fzero(@(x) x*x-2,10)
%x-sqrt(2)

disp("fsolve");
x=fsolve(@(x) x*x-2,1)
x-sqrt(2)


x=fsolve(@(x) x*x-2,2)
x-sqrt(2)


[x,fval,info,output]=fsolve(@(x) x*x-2,100)
x-sqrt(2)


[x,fval,info,output]=fsolve(@(x) 2*x+sin(x),1)


%try to use analytical derivativelmarcinkowski@wp.pl
optJ=optimset("Jacobian","on");
optnJ=optimset("Jacobian","off");
function [y,dy]=sq(x)
  y=x*x;dy=2*x;
end 
 
x=fsolve(@sq,2,optJ)


%2x+cos(x)
function [y,dy]=f1(x)
  y=2*x+cos(x);
  if (nargout>1) 
    dy=2-sin(x) 
  end  
  %no semicolon to see if it is really called
end 
x1=fsolve(@f1,2)
optJ=optimset("Jacobian","on");
x2=fsolve(@f1,2,optJ)
x1-x2




%computing a function given in an implicit way
%F(x,y)=x*x+2*y*y-1
%compute the discrete values (at discrete x) of 
%y(x) defined by F(x,y(x))=0 for x\(0,1)
%in practice on [0,1-tol)

function z=F(x,y)
  z=x.*x+2*y.*y-1;
end 
tol=eps/2;
M=200;
x=linspace(0,1-tol,M); 

y=zeros(size(x));
y(1)=1/sqrt(2);
fc=0; %function calls
for k=2:M,

[yy,fyy,info,out]=fzero(@(y) F(x(k),y),[0,1/sqrt(2)]); 
 if(info!=1)
  warning("Possible no solution of F(x,y)=0!");
 end 
 y(k)=yy;
 fc+=out.funcCount; 
end
norm(F(x,y),"inf")
fc
graphics_toolkit("gnuplot")
plot(x,y,";computed;",x,sqrt((1-x.*x)*0.5))
pause(1);
%semilogy(x,y-sqrt((1-x.*x)*0.5),";error;");pause(1);
%getting the full positive branch
xx=[-fliplr(x),x];
yy=[fliplr(y),y];
plot(x,y,";y(x):F(x,y(x)=0;");pause(1);

%the graph of the inverse%plot the graph of the inverse of M*x-cos(x)
%on [-M,M] |M|>1 M=1,1000
f=@(x,M) M*x-cos(x)
x=linspace(-1,1,200);
M=1;
y=f(x,M);
subplot(2,1,1);
plot(x,y);
subplot(2,1,2);
plot(y,x);pause(1);
%same for quickly growing function
M=1000;
y=f(x,M);
subplot(2,1,1);
plot(x,y);
subplot(2,1,2);
plot(y,x);pause(1);
%looks OK

%f(x)=tan(x*x)
%f=@(x) tan(x.*x); $f: [0,\sqrt(pi/2))--> [0,+\infty)
%plot the graphs of the inverse on [0,inf) in practise [0,100)
f=@(x) tan(x.*x); 
a=sqrt(pi*0.5);
x=linspace(0,a*(1-1e-3),200);
y=f(x);
subplot(2,1,1);
plot(x,y,"*");
subplot(2,1,2);
plot(y,x,"*");pause(1);
y(end)-y(end-1)

%HM the difference between  two last y points is huge...
%the other way is to ompute the value o the inverse function
y=linspace(0,100,300);
x=zeros(size(y));
fc=0;
for k=2:300,
  [xx,fxx,info,out]=fzero(@(x) f(x)-y(k),[0,a-eps/2]);
  if(info!=1)
   warning("No solution!");
  end 
  x(k)=xx;
  fc+=out.funcCount;
endfor
subplot(1,1,1);
plot(y,x,"*");
fc


%plot the graph of inverse taking a dense x meshes close to sqrt(pi/2)
x=a*(1-logspace(0,-2,300));
y=f(x);
plot(y,x,"*")