Скачиваний:
13
Добавлен:
01.05.2014
Размер:
2.01 Кб
Скачать

#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef char bool;
const bool true=1,
		false=0;

const double FirstStep = 0.001;
const double Epsilon   = 0.001;
const double Delta     = 0.1*Epsilon;
const double xBegin   = 1;

bool SelectSecondPoint(double&);
inline double Func(double);
inline double NextPoint(double,double&);
void SvennFunc(double&,double&);
void GoldMetod1(double,double,double&,double&);

int main(void)
{
	double X1,X2,FMin,X;
	clrscr();
	SvennFunc(X1,X2);
	GoldMetod1(X1,X2,X,FMin);
	printf("\nX=%f F(X)=%f",X,FMin);
	return 0;
}
void GoldMetod1(double A,double B,double& X,double&FMin)
{
	double L=0,M=0;
	M=A+0.618*(B-A);
	L=A+0.382*(B-A);
	int k=0;
	while((B-A)>Epsilon&&k<300)
	{
		if(Func(L)<Func(M))
		{
			B=M;
			M=L;
			L=A+0.382*(B-A);

		}
		else
		{
			A=L;
			L=M;
			M=A+0.618*(B-A);
		}
		k++;
	}
	X=(A+B)/2;
	FMin=Func(X);
}
void SvennFunc(double&A,double&B)
{
	double Step=0,A1=0,B1=0;

	//------------------------------------- Svenn Metods
	if(SelectSecondPoint(Step))
	{
		double Curr,Prev,Prev2;
		Curr=Prev=xBegin;
		do
		{
			Prev=Curr;
			Curr=NextPoint(Curr,Step);
			printf("\nNew point X=%f F(X)=%f",Curr,Func(Curr));
		}
		while(Func(Curr)<Func(Prev));

		Prev2=Prev-Step/2;
		if(Step<0)
		{
			A1=Curr;
			B1=Prev2;
		}
		else
		{
			A1=Prev2;
			B1=Curr;
		}
	}
	else
	{
		A1=xBegin-FirstStep;
		B1=xBegin+FirstStep;
	}
	A=A1;
	B=B1;
}
bool SelectSecondPoint(double& Step)
{

	if((Func(xBegin-FirstStep)>Func(xBegin))&&(Func(xBegin+FirstStep)>Func(xBegin)))
	{
		Step=0;
		return 0;
	}
	if(Func(xBegin+FirstStep)-Func(xBegin)>0)
	{
		Step=-FirstStep;
		return 1;
	}
	if(Func(xBegin-FirstStep)-Func(xBegin)>0)
	{
		Step=FirstStep;
		return 1;
	}
	return 1;

}
inline double Func(double X)
{
	return 2*X*X-exp(X);
}
inline double NextPoint(double Prev,double& Step)
{
	Step=Step*2;
	return (Prev+Step);
}
Соседние файлы в папке all