% Tund 7, ülesanne 2
% joonis
ezplot('x^2+2*y-8=0')
hold on
ezplot('x+y^2-y-3=0')
hold off
grid on
% alglähendid (-3.5,-2), (-1.5,2.7), (2.2,1.4) ja (2.9,-0.1)
% võrrandisüsteem vektorfunktsioonina
% z=(x,y), x=z(1) ja y=z(2)
F=@(z) [z(1)^2+2*z(2)-8;z(1)+z(2)^2-z(2)-3]; % veeruvektor

% lahendame Newtoni meetodiga
z=[-1.5;2.7]; % veeruvektor
i=0;
while norm(F(z),1)>10^(-6)
   Ftuletis=[2*z(1),2;1,2*z(2)-1];
   z=z-inv(Ftuletis)*F(z);
   i=i+1;
end
lahend1=z
sammud1=i

z=[-3.5;-2]; % veeruvektor
i=0;
while norm(F(z),1)>10^(-6)
   Ftuletis=[2*z(1),2;1,2*z(2)-1];
   z=z-inv(Ftuletis)*F(z);
   i=i+1;
end
lahend1=z
sammud1=i

% lahendame hariliku it. meetodiga
% uurime koondumist
x=-3.5;
y=-2;
Gtuletis=[0,-1/sqrt(8-2*y);-1/(2*sqrt(3+y-x)),1/(2*sqrt(3+y-x))];
norm(Gtuletis,1) % sobib, <1
x=-1.5;
y=2.7;
Gtuletis=[0,-1/sqrt(8-2*y);-1/(2*sqrt(3+y-x)),1/(2*sqrt(3+y-x))];
norm(Gtuletis,1) % sobib, <1
x=2.2;
y=1.4;
Gtuletis=[0,-1/sqrt(8-2*y);-1/(2*sqrt(3+y-x)),1/(2*sqrt(3+y-x))];
norm(Gtuletis,1) % sobib, <1
x=2.9;
y=-0.2;
Gtuletis=[0,-1/sqrt(8-2*y);-1/(2*sqrt(3+y-x)),1/(2*sqrt(3+y-x))];
norm(Gtuletis,1) % ei sobi

% lahendame kolme esimese alglähendi korral ära
z=[-3.5,-2];
i=0;
while norm(F(z),1)>10^(-6)
   z(1)=-sqrt(8-2*z(2));
   z(2)=-sqrt(3+z(2)-z(1));
   i=i+1;
end
lahend1h=z
sammud1h=i
[sammud1,sammud1h]

z=[-1.5,2.7];
i=0;
while norm(F(z),1)>10^(-6)
   z(1)=-sqrt(8-2*z(2));
   z(2)=sqrt(3+z(2)-z(1));
   i=i+1;
end
lahend2h=z
sammud2h=i

z=[2.2,1.4];
i=0;
while norm(F(z),1)>10^(-6)
   z(1)=sqrt(8-2*z(2));
   z(2)=sqrt(3+z(2)-z(1));
   i=i+1;
end
lahend3h=z
sammud3h=i

% valisime uue g_2, uurime koondumist
x=2.9;
y=-0.1;
uusGtuletis=[0,-1/sqrt(8-2*y);1,2*y];
norm(uusGtuletis,1) % ~ <1
z=[2.9,-0.1];
i=0;
while norm(F(z),1)>10^(-6)
   z(1)=sqrt(8-2*z(2));
   z(2)=z(1)+z(2)^2-3;
   i=i+1;
end
lahend4h=z
sammud4h=i