#include "declare.h"
void work(void)
{
extern int nfun;
extern float *x1,*y;
extern int n;
extern float *x0,*x1,*eps_i;
extern float eps;
extern int M;
 FILE *ff,*ff1;
 float **s;
 float *c,*xnn,*ss;
 float delta,min_fun=9999.,fi_1,fi_2;
 int i,j,ik,k=0,m=0,is;
 ss=new float [n];
 c=new float [n];
 xnn=new float [n];
 s = new float* [n];
 message();
 for(i=0;i<n;i++) s[i] = new float [n];
 for(i=0;i<n;i++)
   for(j=0;j<n;j++)
    if(i==j) s[i][j] = -1.;
     else
	   s[i][j] = 0.;
 nfun=0;
 x1=new float [n];
 y=new float [n];
 switch(M)
 {
  case 1:  ff = fopen("data31.dat","w");
	   break;
  case 2:  ff = fopen("data32.dat","w");
	   break;
 }
	   ff1 = fopen("tmpfile.tmp","w");
  for(i=0;i<n;i++) fprintf(ff,"%lf ",x0[i]);
  fprintf(ff,"\n");
  for(i=0;i<n;i++) x1[i] = x0[i];
  fi_1 = f(x1);
 fprintf(ff1,"Начальное приближение\n");
 for(i=0;i<n;i++) fprintf(ff1,"%lf ",x0[i]);
 fprintf(ff1,"\n");
do
{
 k += 1;
 for(i=0;i<n;i++) c[i] = x0[i];
 delta = 0.0;
 for(i=0;i<n;i++)  x1[i] = c[i];
 for(ik=0;ik<n;ik++)
 {
  for(i=0;i<n;i++)
      ss[i] = s[i][ik];
  for(i=0;i<n;i++) fprintf(ff,"%lf ",x1[i]);
  fprintf(ff,"\n");
  minim(fi_1,ss,&is);
  for(i=0;i<n;i++) fprintf(ff,"%lf ",x1[i]);
  fprintf(ff,"\n");
  fi_2=f(x1);
  if(delta < (fabs(fi_1-fi_2)))
	     {
	       m=ik; delta=fabs(fi_1-fi_2);
	     }
 }
 for(i=0;i<n;i++) xnn[i] = 2*x1[i]-x0[i];
 min_fun=fi_1;
 fi_1 = fi_2;
 is=1;
 if( ( (f(xnn)>=f(x0) ) || (f(xnn)>=f(x1))) ||
      ( (f(x0)-2*f(x1)+f(xnn))*(f(x0)-f(x1)-delta)*(f(x0)-f(x1)-delta) >=
       0.5*delta*(f(x0)-f(xnn))*(f(x0)-f(xnn)) ) )
    {
	 if(f(xnn)>f(x1))
	   for(i=0;i<n;i++) x0[i] = x1[i];
	 else
	   for(i=0;i<n;i++) x0[i] = xnn[i];
    }
    else
     {
	for(i=0;i<n;i++) ss[i] = xnn[i] - x0[i];
	for(i=0;i<n;i++) x1[i] = xnn[i];
	fi_1=f(x1);
	for(i=0;i<n;i++) fprintf(ff,"%lf ",x1[i]);
	fprintf(ff,"\n");
	minim(fi_2,ss,&is);
	fprintf(ff1,"Шагали из точки xnn=2*x1-x0\n");
	for(i=0;i<n;i++) fprintf(ff1,"%lf ",xnn[i]);
	fprintf(ff1,"\n");
	fprintf(ff1,"в направлении\n");
	for(i=0;i<n;i++) fprintf(ff1,"%lf ",ss[i]);
	fprintf(ff1,"\nи пришли в точку \n");
	for(i=0;i<n;i++) fprintf(ff1,"%lf ",x1[i]);
	fprintf(ff1,"\n");
	for(i=0;i<n;i++) fprintf(ff,"%lf ",x1[i]);
	fprintf(ff,"\n");
	for(i=0;i<n;i++) x0[i] = x1[i];
	for(j=m;j<n-1;j++)
	for(i=0;i<n;i++) s[i][j] = s[i][j+1];
	for(i=0;i<n;i++) s[i][n-1] = ss[i];
	fprintf(ff1,"\nМатрица направлений поиска \n");
	for(j=0;j<n;j++)
	{
	 fprintf(ff1,"\n");
	 for(i=0;i<n;i++)
		  fprintf(ff1,"%lf ",s[i][j]);
	}
	 fprintf(ff1,"\n");
     }
  fi_2 = min_fun;
  min_fun=f(x0);
 fprintf(ff1,"\nТочка минимума\n");
 for(i=0;i<n;i++) fprintf(ff1,"%lf ",x0[i]);
 fprintf(ff1,"\nИтерация  k =  %d\n",k);
 fprintf(ff1,"Значение минимума = %lf \n",min_fun);
 is=1;
 for(i=0;i<n;i++)
    if(fabs(c[i]-x0[i]) > fabs(x0[i])*eps_i[i] )
	is = 0;
}
while ((fabs(fi_2-min_fun) > eps ) && !(is) || (k==1) );
fclose(ff1);
delete ss;
delete c;
delete x1;
delete xnn;
delete y;
fclose(ff);
message();
}