%% myvectorNewtontests.m  Newton tests    
%  28.11.2016 HA.
%
% Choose an n-vector x0 of initial values on a real interval.
% See, which x0(k)'s stay within the intial interval, and which go out.
% Draw histograms and study the geometry of the vectors x0in and x0out
% Further study: x0diverge
%
% call function mynewt, vector-Newton
help mynewt
%%
close all
n=1000;
%n=100;
a=-4;b=4;
%%
x0=linspace(a,b,n);      % Vector of initial points
f=@sin; df=@cos;          % Obj. function and derivative
[sols Niter]=mynewt(f,x0,df);
%%
x0(sols==max(sols))   % Initial points leading to max solution
x0(sols==min(sols))   % Initial points leading to min solution
indmax=find(sols==max(sols))
indmin=find(sols==min(sols))
M=max(sols)

%% How many are out of initial interval
sum(sols > b)
sum(sols < a)

%%
%{
>> sum(sols>4)

ans =

    75

>> sum(sols<-4)

ans =

    75
>> sum(abs(sols)<=4)

ans =

   850
hist ...
%}
%%
in=(sols >= a) & (sols<=b);
nr_in = sum(in)
%%
solsIn=sols(in);
out=~in;
nr_out=sum(out)
solsOut=sols(out);
%histogram(solsIn)
%%
close all
subplot(2,1,1)
 hin=histogram(solsIn,linspace(a,b,n))
subplot(2,1,2)
 hout=histogram(solsOut,linspace(-20,20,n))

%%
clf
solsOut=sols(abs(sols)>4);
hout=histogram(solsOut)
figure
hout100=histogram(solsOut,100)

%%
M=max(sols)
max(abs(f(sols)))  % Values of f at sols.
%%
IndOut=find(abs(sols)>4);
x0_2solsOut=x0(IndOut);  % Initial points leading out of interval
IndIn=find(abs(sols)<=4); 
x0_2solsIn=x0(IndIn);     % Initial points staying in.
%%
figure
clf
plot(x0, f(x0))
hold on
plot(x0_2solsOut,0,'.r') 
plot(x0_2solsIn,0,'.k')   
% Zoom in to see fractal geometry.
% Points near minima and maxima lead far (of course), but the geometry 
% isn't just subintervals.
%
%%
figure
hin=histogram(solsIn,1000)
%%
figure
hout10000=histogram(solsOut,10000)
