%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         8. practice         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Nonlinear dynamics systems  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         2019.12.04.         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%           Fractals          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Newton approximation method
clear all;

Accuracy = 0.01;
x = -0.5: 0.001: 0.5;
y = x';
[X,Y] = meshgrid(x,y);
meret=length(x);

figure
xlim([0 meret])              
ylim([0 meret])              
hold on;

z0 = X + 1i*Y; %complex plain
original=1.*z0;
depth = 32;% 20, 2, 4, 8, 16, 32, %you can see the development of the figure
for k = 1:depth
	z0 = z0 - (z0.*z0.*z0 + 1)./(3.*z0.*z0); %Newton approximation for solving the x^3+1=0 equation
    %3 solutions: -1; 1/2+i*sqrt(3/2); 1/2-i*sqrt(3/2);
    %z0 = z0 - (z0.*z0.*z0 -2*z0 + 2)./(3.*z0.*z0-2);
end
equ_root=roots([1 0 0 1]) 
%equ_root=roots([1 0 -2 2])
% color the points (20,40,60) based on which root the system approximates from this initial point  
Red=(abs(z0 - equ_root(1))<Accuracy)*60;
Green=(abs(z0 - equ_root(2))<Accuracy)*40;
Blue=(abs(z0 - equ_root(3))<Accuracy)*20;
%points that don't convergate whit this iteration number stays 0:=dark blue
imagesc(Red+Green+Blue)   %sum and show the three color matrices

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%
% count dark blue cells:

% osszesitett = Red+Green+Blue;
% counter_1=sum(sum(osszesitett == 0)); % first idea: count dark blue cells

epsz = 2; %resolution
n = meret/epsz; %magnification factor

%{
% draw grid lines with epsz precision
for i = 0:epsz:meret
    i = i+0.5;
    plot([i,i],[0,meret]);
    plot([0,meret],[i,i]);   
end
%}

counter_1 = 0;
osszesitett = Red+Green+Blue;
for a = 1:epsz:(meret-epsz)
    for b = 1:epsz:(meret-epsz)
        osszesitett_resz = osszesitett(a:(epsz+a-1), b:(epsz+b-1));
        
        %border cells: cells with more than one color or if the root is undefined (dark blue cells)
        if length(unique(osszesitett_resz))~=1 || sum(sum(osszesitett_resz == 0))==numel(osszesitett_resz)
            counter_1 = counter_1 +1;
        end
        
    end
end

%show the result of box counting (based on the 2. method):
counter_1

% define box dimension: log(munber of boundary cells*resolution)/log(magnification)
dimension= (log(counter_1*(epsz)))/(log(n))
%}

%other equations: e.g.: x^3-1; x^3-2x+2