Пример #1
0
double Graph::
golden(const int function,double xmin,double xcenter,double xmax,bool solveMax,double tolerance)
{
    static const double phi=.5*(1.+sqrt(5.)),resPhi=2-phi;

    //double xcenter=.5*(xmin+xmax);
    double xnew=xcenter+resPhi*(xmax-xcenter);
        
    if(fabs(xmax-xmin)<1e-5*(fabs(xnew)+fabs(xcenter))) return (xmax+xmin)/2;

#if 0
    double f_xcenter=funcs.eval(function,xcenter);
    double f_xnew=funcs.eval(function,xnew);
    if(solveMax){
        f_xcenter*=-1;
        f_xnew*=-1;
    }

    if(f_xnew<f_xcenter) return golden(function,xcenter,xnew,xmax,solveMax,tolerance);
    else return golden(function,xnew,xcenter,xmin,solveMax,tolerance);
#else
    UNUSED(function);
    UNUSED(solveMax);
    UNUSED(tolerance);
#endif
    return 0;
}
Пример #2
0
Файл: Grad.cpp Проект: Neolus/C
/***定义梯度函数求解极值函数**********/
double* grad(double (*f)(double,double),double *p,double a,double b,double tol,FILE *fp) //f数学公式,p搜索起点的向量,a、b用于求解黄金分割时的范围、tol实验精度、fp指向文本
{
	double s[2],sa,ta,r;
	double hmin;
	int i;
	solveS(p[0],p[1],s);  //求解搜索方向向量
	hmin=golden(gema,a,b,tol,s,p,fp); //求解gama极小值

	for(i=0;i<2;i++)
	{
		p[i]=p[i]+hmin*s[i];  //计算新的搜索点
		printf("%0.8f\t",p[i]);
		fprintf(fp,"%0.8f\t",p[i]);	
	}

	r=sqrt(f(p[0],p[1])); //求出到定点的距离
	printf("%0.8f\n",r);
	fprintf(fp,"%0.8f\n",r);


	sa=sqrt(s[0]*s[0]+s[1]*s[1]); 
	ta=hmin*sa; //计算变化的距离



	if(fabs(ta)<10*tol)  return p;  //如果变化距离小于精度,结束运算

	 p=grad(f,p,a,b,tol,fp); //否则继续搜索。

	 return p;

}
Пример #3
0
void Kaffee::golden()
{
    dirty = TRUE;
    t = (t == Red ? Golden : Red);
    int r = random() % 40000;
    QTimer::singleShot( r, this, SLOT(golden()) );
}
Пример #4
0
Kaffee::Kaffee(int pos, int r1, int r2)
{
    p = pos;
    t = Red;
    r = r2;
    QTimer::singleShot( r1, this, SLOT(golden()) );
    dirty = true;
}
Пример #5
0
Kaffee::Kaffee(int pos)
{
    p = pos;
    t = Red;
    int r = random() % 40000;
    QTimer::singleShot( r, this, SLOT(golden()) );
    dirty = TRUE;
}
Пример #6
0
void testRoot(){

 printf("\nRoot finding and minimisation\n");
 golden(functionTest3,0,2);
 golden(functionTest1,3,7);
 golden(functionTest2,5,7);
 golden(poly,-0.5,1.0); 

 brute (poly,-1.0,1.0, 0.0001); 
 brute (functionTest1,3,7, 0.0001); 
 secant(poly,0.0,1.0);
 newton(poly, dpoly, 0.0); 
 regulaFalsi(poly,-1.0,1.0); 
 bisect(poly,-1.0,1.0);
 fixedPointIteration(cosine,1.0); 
 squareRoot(20); 
 
} 
Пример #7
0
void Graph::solveMin(const int function, double xmin, double xmax, bool solveMax) {
    if (xmax < xmin) std::swap(xmin, xmax);
    double xsolve = golden(function, xmin, .5 * (xmin + xmax), xmax, solveMax, 1e-5);
    rootX = xsolve;
    rootY = funcs.eval(function, xsolve);
    rootShow = false;
    minShow = true;
    repaint();
}
Пример #8
0
REAL cIEC_OptimCurDir::Optim(REAL aV0,REAL aV1)
{
    REAL aX = aV0;
    REAL bX = aV1;
    REAL cX; 
    REAL aY,bY,cY;

    mnbrack(&aX,&bX,&cX,&aY,&bY,&cY);

    REAL XMin;
    golden(aX,bX,cX,1e-5,&XMin);

    return XMin;
}
Пример #9
0
void BenchDMR::test()
{

    REAL ax=-1,bx=1,cx,fa,fb,fc;
    mnbrack(&ax,&bx,&cx,&fa,&fb,&fc);

    REAL xmin1;
    golden(ax,bx,cx,1e-15,&xmin1);

    if (_pol.degre() <= 4)
       BENCH_ASSERT(std::abs(_dpol(xmin1)) < BIG_epsilon);
    BENCH_ASSERT(std::abs(_dpol(xmin1)) < GIGANTESQUE_epsilon);

    Pt2dr aP = brent(true);
    if (_pol.degre() <= 4)
       BENCH_ASSERT(std::abs(_dpol(aP.x)) < BIG_epsilon);
    BENCH_ASSERT(std::abs(_dpol(aP.x)) < GIGANTESQUE_epsilon);

}
Пример #10
0
bool  cOneTestLSQ::OneOptimOnLine()
{
   if (! OneLSQItere())
      return false;

   double aL0 = 0;
   double aC0 =  mCorel0LSQ;

   double aL1 = 1;
   double aC1 =  CorrelOnLine(aL1);
   if (aC1 == -1) 
      return false;

   if (aC1<aC0) 
      return false;

   double aL2 = std::max(2.0,TheNormMinLSQ/euclid(mDepLSQ));
   double aC2 =  CorrelOnLine(aL2);

   if (aC2 == -1) 
      return false;

   while (aC2 > aC1)
   {
       aL0 = aL1;
       aC0 = aC1;

       aL1 = aL2;
       aC1 = aC2;
 
       aL2 *= TheMult;
       aC2 =  CorrelOnLine(aL2);
       if (aC2 == -1) 
           return false;
   }

   double aLMin;
   golden(aL0,aL1,aL2,1e-3,&aLMin);

   SetPIm2(mIm2->PVois(0,0) +mDepLSQ *aLMin);
   return true;

}
DEF_TEST(SkRecordingAccuracyXfermode, reporter) {
#define FINEGRAIN 0
    const Drawer drawer;

    BitmapBackedCanvasStrategy golden(drawer.imageInfo());
    PictureStrategy picture(drawer.imageInfo());

#if !FINEGRAIN
    unsigned numErrors = 0;
    SkString errors;
#endif

    for (int iMode = 0; iMode < int(SkBlendMode::kLastMode); iMode++) {
        const SkRect& clip = SkRect::MakeXYWH(100, 0, 100, 100);
        SkBlendMode mode = SkBlendMode(iMode);

        const SkBitmap& goldenBM = golden.recordAndReplay(drawer, clip, mode);
        const SkBitmap& pictureBM = picture.recordAndReplay(drawer, clip, mode);

        size_t pixelsSize = goldenBM.computeByteSize();
        REPORTER_ASSERT(reporter, pixelsSize == pictureBM.computeByteSize());

        // The pixel arrays should match.
#if FINEGRAIN
        REPORTER_ASSERT(reporter,
                        0 == memcmp(goldenBM.getPixels(), pictureBM.getPixels(), pixelsSize));
#else
        if (memcmp(goldenBM.getPixels(), pictureBM.getPixels(), pixelsSize)) {
            numErrors++;
            errors.appendf("For SkXfermode %d %s:    SkPictureRecorder bitmap is wrong\n",
                           iMode, SkBlendMode_Name(mode));
        }
#endif
    }

#if !FINEGRAIN
    REPORTER_ASSERT(reporter, 0 == numErrors, errors.c_str());
#endif
}
Пример #12
0
Файл: Grad.cpp Проект: Neolus/C
/******定义黄金分割函数*************/
double golden(double (*f)(double,double *,double *),double a,double b,double tol,double *s,double *p,FILE *fp) //f为数学函数,i为对应题目0-3对应a-d,a为左端点,b为右端点,tol为精度,fp指向文本
{
	double r;
	double a1,b1,c,d,length;
	double tc,td,z;
	r=0.5*(-1+sqrt(5.));
	length=b-a; 
	c=a+(1-r)*length;  //计算ck
	d=b-(1-r)*length;  //计算dk
	tc=f(c,s,p); //计算两点对应的函数值
	td=f(d,s,p);

	if(tc<td)  //判断下一个ak,bk的取值
	{
		a1=a;
		b1=d;
	}
	else
	{
		a1=c;
		b1=b;
	}


	if(fabs(a1-b1)>tol)  //如果没有满足精度,继续细分
	{
		z=golden(f,a1,b1,tol,s,p,fp);
	}

	else
	{
		z=0.5*(a1+b1);  //取最后两点的中点为极值点

	}


	return z;

}
// Compute the price of a bermudan swaption.
static int MC_BermSwpaption_Andersen(NumFunc_1 *p, Libor *ptLib, Swaption *ptBermSwpt, Volatility *ptVol, double Nominal, long NbrMCsimulation_param, long NbrMCsimulation, int NbrStepPerTenor, int generator, int flag_numeraire, int q, double *PriceBermSwp)
{
  int alpha, beta, i, NbrExerciseDates;
  double tenor, numeraire_0;
  double ax, bx,  cx, tol, xmin;

  AndersenStruct andersen_struct;
  PnlFunc FuncToMinimize;

  Create_AndersenStruct(&andersen_struct);

  //Nfac = ptVol->numberOfFactors;
  //N = ptLib->numberOfMaturities;
  tenor = ptBermSwpt->tenor;
  alpha = pnl_iround(ptBermSwpt->swaptionMaturity/tenor); // T(alpha) is the swaption maturity
  beta  = pnl_iround(ptBermSwpt->swapMaturity/tenor); // T(beta) is the swap maturity
  NbrExerciseDates = beta-alpha;
  

  numeraire_0 = Numeraire(0, ptLib, flag_numeraire);

  tol = 1e-10;
  q = MIN(q, NbrExerciseDates-1); // The maximum number of kink-points that can be used is NbrExerciseDates-1.
  q = MAX(1, q); // q must be greater than zero.

  FuncToMinimize.function = &func_to_minimize;
  FuncToMinimize.params = &andersen_struct;

  // Initialize the structure andersen_struct using "NbrMCsimulation_param" paths.
  // We will use these paths to estimates the optimal parameters of exercise strategy.
  Init_AndersenStruct(&andersen_struct, ptLib, ptBermSwpt, ptVol, p, NbrMCsimulation_param, NbrStepPerTenor, generator, flag_numeraire, Nominal, q);

  // At maturity, the parameter is null, because we exercise whenever payoff is positif.
  pnl_vect_set_zero(andersen_struct.AndersenParams);

  ax = 0; // lower point for GoldenSearch method
  cx = andersen_struct.H_max; // upper point for GoldenSectionSearch method
  bx = 0.5*(ax+cx); // middle point for GoldenSectionSearch method

  for (i=q-1; i>=0; i--)
    {
      // Index of exercise date where we compute parameter of exercise strategy.
      andersen_struct.j_start = pnl_vect_int_get(andersen_struct.AndersenIndices, i);

      // Find optimal parameter at current exercise date.
      golden(&FuncToMinimize, ax, bx, cx, tol, &xmin);

      // Store this parameter in AndersenParams.
      LET(andersen_struct.AndersenParams, andersen_struct.j_start) = xmin;

      ax = 0.5*xmin;
      bx = 0.5*(ax+cx);
    }

  // We simulate another set of Libor paths, independants of the ones used to estimate the parameters of exercise strategy.
  // In general, choose NbrMCsimulation >> NbrMCsimulation_param.
  Init_AndersenStruct(&andersen_struct, ptLib, ptBermSwpt, ptVol, p, NbrMCsimulation, NbrStepPerTenor, generator, flag_numeraire, Nominal, q);

  // Finaly, we use the found parameters to estimate the price of bermudan swaption following.
  andersen_struct.j_start = 0;
  *PriceBermSwp = numeraire_0*AmOption_Price_Andersen(&andersen_struct);

  // Free memory.
  Free_AndersenStruct(&andersen_struct);

  return OK;
}
Пример #14
0
void Kaffee::golden()
{
    dirty = true;
    t = (t == Red ? Golden : Red);
    QTimer::singleShot( r, this, SLOT(golden()) );
}
Пример #15
0
Файл: icm.cpp Проект: pietg/book
void 	ICM_iteration(int N, int n, int K, int nlast, int first[], int m[], int **freq, int **ind, double **y,
					   double **F, double **F_new, double **cumw, double **cs, double **v, double **w,
                      double **nabla, double *lambda1, double *alpha1)
{
	int 	i,j,k;
	double 	a,lambda,alpha;
    
	lambda=*lambda1;
	
	for (k=1;k<=K;k++)
	{
		for (i=1;i<=m[k];i++)
			v[k][i]=w[k][i]=0;
	}
    
	
	for (k=1;k<=K;k++)
	{
		j=0;
		for (i=first[k];i<=n;i++)
		{
			if (freq[k][i]>0)
			{
				j++;
				v[k][j] = freq[k][i]/(N*F[k][i]);
				w[k][j] = freq[k][i]/(N*SQR(F[k][i]));
			}
            if (freq[0][i]>0)
            {
                v[k][j] -= freq[0][i]/(N*(1-F[K+1][i]));
                w[k][j] += freq[0][i]/(N*SQR(1-F[K+1][i]));
			}
		}
		
		if (nlast<n)
			v[k][m[k]] -=lambda;
		
		for (i=1;i<=m[k];i++)
			v[k][i] += w[k][i]*F[k][ind[k][i]];
	}
	
	cumsum(K,m,v,cs);
	
	convexmin(K,m,cumw,cs,w,y);
    
	Compute_F(K,n,freq,first,y,F_new);
	
	if (F_new[K+1][nlast]>=1)
	{
		a=(1-F[K+1][nlast])/(F_new[K+1][nlast]-F[K+1][nlast]);
		for (k=1;k<=K;k++)
		{
			for (i=first[k];i<=n;i++)
				F_new[k][i]=F[k][i]+a*(F_new[k][i]-F[k][i]);
		}
		compute_Fplus(n,K,F_new);
		
		for (k=1;k<=K;k++)
		{
			j=0;
			for (i=first[k];i<=n;i++)
			{
				if (freq[k][i]>0)
				{
					j++;
					y[k][j]=F_new[k][i];
				}
			}
		}
	}
    
    if (f_alpha_prime(N,n,K,freq,1.0,F,F_new,lambda)<=0) alpha=1;
    else
        alpha=golden(N,n,K,freq,F,F_new,0.1,1,f_alpha,lambda);
    
	for (k=1;k<=K;k++)
	{
		for (i=first[k];i<=n;i++)
			F[k][i] += alpha*(F_new[k][i]-F[k][i]);
	}
	
	compute_Fplus(n,K,F);
    
	if (nlast<n)
		lambda=compute_lambda(N,n,K,freq,F);
	else
		lambda=0;
	
	compute_nabla(N,n,K,first,m,freq,F,lambda,nabla);
	
	*lambda1=lambda;
	*alpha1=alpha;
}