Numerical Recipes in C
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供盤州網(wǎng)站建設、盤州做網(wǎng)站、盤州網(wǎng)站設計、盤州網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、盤州企業(yè)網(wǎng)站模板建站服務,十載盤州做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。
一書及所附程序,有完整程序。不過我封裝了它的C++版本,可以對但參數(shù)或多參數(shù)求極值,完整的頭文件為:
#ifndef __OPTIMIZATION_H__
#define __OPTIMIZATION_H__
//////////////////////////////////////////////////////////////////////////
// class TOptimization
//
// $ 求函數(shù)一個或多個參數(shù)的最小值
//
// 該類默認對一個參數(shù)優(yōu)化,一般只要輸入優(yōu)化參數(shù)數(shù)目
// 優(yōu)化目標函數(shù)就可以使用。
//
// ...主要代碼來自:
// Numerical Recipes in C++
// The Art of Scientific Computing
// Second Edition
// William H. Press Saul A. Teukolsky
// William T. Vetterling Brian P. Flannery
//
// 中譯本:
// C++ 數(shù)值算法(第二版) 胡健偉 趙志勇 薛運華 等譯
// 電子工業(yè)出版社 北京 (2005)
//
// Author: Jian Feng
// Email: fengj@tom.com
// Dec. 9, 2006
//
//////////////////////////////////////////////////////////////////////////
//
// 輸入函數(shù):
//
// @MaxIterationStep: 最大迭代次數(shù), 默認 1000
// @ParameterNumbers: 優(yōu)化參數(shù)數(shù)目, 默認 1
// @InitMatrix: 初始化矩陣參數(shù)(N*N), 默認
// @Tolerance: 容許公差, 默認 1E-7
//
// 執(zhí)行函數(shù):
//
// @ExecutePowell: 利用powell方法進行多參數(shù)優(yōu)化
// @ExecuteBrent: 利用brent方法進行單參數(shù)優(yōu)化
//
// 輸出函數(shù):
//
// @OptimizatedParameters: 優(yōu)化結果數(shù)據(jù)
// @ObjectiveFunctionValue: 目標函數(shù)在優(yōu)化值處的值
//
// 使用示例:
//
// 1. 單參數(shù)
// double objfun(double a){
// double sum = 0;
// for(int i = 0; i DataPoints; ++i)
// sum += SQR(Exps[i] - Theo(a));
// }
// double value
// TOptimization opt;
// if(opt.ExecuteBrent(objfun, -10, -1)) opt.OptimizatedParameters(value);
//
// 2. 多參數(shù)
// double objfun(double *a){
// double sum = 0;
// for(int i = 0; i DataPoints; ++i)
// sum += SQR(Exps[i] - Theo(a));
// }
// double value[3]
// TOptimization opt(3);
// double ival[3] = ;
// if(opt.ExecutePowell(objfun, ival)) opt.OptimizatedParameters(value);
//
namespace{
static int ncom; //公用變量
static double *pcom_p; //公用變量
static double *xicom_p; //公用變量
static double (*nrfunc)(double*); //公用函數(shù)指針
}
class TOptimization
{
private:
typedef double (*Reff)(double *);
typedef double (*Ptrf)(double );
public:
TOptimization(int n = 1);
~TOptimization()
//主要方法
void ParameterNumbers(int n)
//利用powell方法對一個或多個參數(shù)優(yōu)化
bool ExecutePowell(Reff obj, double *a = 0);
//利用brent方法對一個參數(shù)優(yōu)化,需給出參數(shù)所在的區(qū)間
bool ExecuteBrent(Ptrf obj, double vFrom = 0, double vTo = 1);
void OptimizatedParameters(double *a)
void OptimizatedParameters(double a)
//void OptimizatedParameters(double *a){
// if(method) for(int i=0; inum; ++i) a[i]=coef[i];
// else *a = vmin;
//}
//其它方法
void InitMatrix(double **m)
{
for(int i=0; inum; ++i)
for(int j = 0; jnum; ++j)
matx[i][j]=m[i][j];
setm = true;
}
void MaxIterationStep(int s)
void Tolerance(double eps)
double ObjectiveFunctionValue()const
private:
double brent(double ax, double bx, double cx, Ptrf f, double tol, double xmin, int flag);
void mnbrak(double ax, double bx, double cx, double fa, double fb, double fc, Ptrf func);
void linmin(double *p, double *xi, double fret, Reff func);
bool powell(double *p, double **xi, double ftol, int iter, double fret, Reff func);
void shft2(double a, double b, const double c)
void shft3(double a, double b, double c, const double d)
double SQR(double x)
void SWAP(double a, double b)
double SIGN(const double a, const double b)
double MAX(const double a, const double b)
void AllocateMemory();
void FreeMemory();
static double f1dim(double x)
{
int j;
double *xt = new double [ncom];
//Vec_Dp pcom=*pcom_p,xicom=*xicom_p;
double *pcom = pcom_p, *xicom = xicom_p;
for (j=0;jncom;j++)
xt[j]=pcom[j]+x*xicom[j];
//delete []xt;
double val = nrfunc(xt);
delete []xt;
return val;
}
bool setm; //是否設置優(yōu)化方向初始矩陣
int num; //優(yōu)化參數(shù)
int ITMAX; //最大迭代數(shù)
int iter; //實際迭代步數(shù)
int method; //優(yōu)化方法 0: 1-D brent, 2: M-D Powell
double vmin; //一維優(yōu)化參數(shù)
double ftol; //容許差
double fret; //目標函數(shù)值
double *coef; //多維優(yōu)化參數(shù)值
double **matx; //多維優(yōu)化參數(shù)方向的初始值
};
//////////////////////////////////////////////////////////////////////////
inline TOptimization::TOptimization(int n )
{
num = n;
ftol = 1e-7;
ITMAX = 1000;
iter = 0;
fret = 0.;
vmin = 0.;
method = 0;
setm = false;
AllocateMemory();
}
inline void TOptimization::AllocateMemory()
{
pcom_p = new double [num];
xicom_p = new double [num];
coef = new double [num];
matx = new double *[num];
for(int i = 0; i num; ++i)
{
coef[i] = 0.;
matx[i] = new double [num];
for(int j = 0; j num; ++j)
matx[i][j]=(i == j ? 1.0 : 0.0);
}
}
inline void TOptimization::FreeMemory()
{
for(int i = 0; i num; ++i)
{
delete []matx[i];
}
delete []matx;
delete []pcom_p;
delete []xicom_p;
delete []coef;
}
inline bool TOptimization::ExecutePowell(Reff obj, double *a)
{
method = 1;
if(a)
for(int i = 0; i num; ++i) coef[i] = a[i];
return powell(coef, matx, ftol, iter, fret, obj);
}
inline bool TOptimization::ExecuteBrent(Ptrf obj, double vFrom, double vTo)
{
method = 0;
int flag;
double cx, fa, fb, fc;
mnbrak(vFrom,vTo,cx,fa,fb,fc,obj);
fret = brent(vFrom,vTo,cx,obj, ftol,vmin, flag);
return flag ? true : false;
}
inline void TOptimization::mnbrak(double ax, double bx, double cx, double fa,
double fb, double fc, Ptrf func)
{
const double GOLD=1.618034,GLIMIT=100.0,TINY=1.0e-20;
double ulim,u,r,q,fu;
fa=func(ax);
fb=func(bx);
if (fb fa) {
SWAP(ax,bx);
SWAP(fb,fa);
}
cx=bx+GOLD*(bx-ax);
fc=func(cx);
while (fb fc) {
r=(bx-ax)*(fb-fc);
q=(bx-cx)*(fb-fa);
u=bx-((bx-cx)*q-(bx-ax)*r)/
(2.0*SIGN(MAX(fabs(q-r),TINY),q-r));
ulim=bx+GLIMIT*(cx-bx);
if ((bx-u)*(u-cx) 0.0) {
fu=func(u);
if (fu fc) {
ax=bx;
bx=u;
fa=fb;
fb=fu;
return;
} else if (fu fb) {
cx=u;
fc=fu;
return;
}
u=cx+GOLD*(cx-bx);
fu=func(u);
} else if ((cx-u)*(u-ulim) 0.0) {
fu=func(u);
if (fu fc) {
shft3(bx,cx,u,cx+GOLD*(cx-bx));
shft3(fb,fc,fu,func(u));
}
} else if ((u-ulim)*(ulim-cx) = 0.0) {
u=ulim;
fu=func(u);
} else {
u=cx+GOLD*(cx-bx);
fu=func(u);
}
shft3(ax,bx,cx,u);
shft3(fa,fb,fc,fu);
}
}
inline double TOptimization::brent(double ax, double bx, double cx,
Ptrf f, double tol, double xmin, int flag)
{
flag = 1;
const double CGOLD=0.3819660;
const double ZEPS=1.0e-20;
int iter;
double a,b,d=0.0,etemp,fu,fv,fw,fx;
double p,q,r,tol1,tol2,u,v,w,x,xm;
double e=0.0;
a=(ax cx ? ax : cx);
b=(ax cx ? ax : cx);
x=w=v=bx;
fw=fv=fx=f(x);
for (iter=0;iterITMAX;iter++) {
xm=0.5*(a+b);
tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
if (fabs(x-xm) = (tol2-0.5*(b-a))) {
xmin=x;
return fx;
}
if (fabs(e) tol1) {
r=(x-w)*(fx-fv);
q=(x-v)*(fx-fw);
p=(x-v)*q-(x-w)*r;
q=2.0*(q-r);
if (q 0.0) p = -p;
q=fabs(q);
etemp=e;
e=d;
if (fabs(p) = fabs(0.5*q*etemp) || p = q*(a-x) || p = q*(b-x))
d=CGOLD*(e=(x = xm ? a-x : b-x));
else {
d=p/q;
u=x+d;
if (u-a tol2 || b-u tol2)
d=SIGN(tol1,xm-x);
}
} else {
d=CGOLD*(e=(x = xm ? a-x : b-x));
}
u=(fabs(d) = tol1 ? x+d : x+SIGN(tol1,d));
fu=f(u);
if (fu = fx) {
if (u = x) a=x; else b=x;
shft3(v,w,x,u);
shft3(fv,fw,fx,fu);
} else {
if (u x) a=u; else b=u;
if (fu = fw || w == x) {
v=w;
w=u;
fv=fw;
fw=fu;
} else if (fu = fv || v == x || v == w) {
v=u;
fv=fu;
}
}
}
flag = 0;
xmin=x;
return fx;
}
inline void TOptimization::linmin(double *p, double *xi, double fret, Reff func)
{
int j, flag;
const double TOL=1.0e-8;
double xx,xmin,fx,fb,fa,bx,ax;
int n=num;
ncom=n;
//pcom_p=new Vec_Dp(n);
//xicom_p=new Vec_Dp(n);
nrfunc=func;
//Vec_Dp pcom=*pcom_p,xicom=*xicom_p;
double *pcom = pcom_p, *xicom = xicom_p;
for (j=0;jn;j++) {
pcom[j]=p[j];
xicom[j]=xi[j];
}
ax=0.0;
xx=1.0;
mnbrak(ax,xx,bx,fa,fx,fb,f1dim);
fret=brent(ax,xx,bx,f1dim,TOL,xmin, flag);
for (j=0;jn;j++) {
xi[j] *= xmin;
p[j] += xi[j];
}
//delete xicom_p;
//delete pcom_p;
}
inline bool TOptimization::powell(double *p, double **xi, double ftol, int iter,
double fret, Reff func)
{
const int ITMAX=500;
const double TINY=1.0e-20;
int i,j,ibig;
double del,fp,fptt,t;
int n=num;
//Vec_Dp pt(n),ptt(n),xit(n);
double *pt, *ptt, *xit;
for(i = 0; i n; ++i)
{
pt = new double [n];
ptt = new double [n];
xit = new double [n];
}
fret=func(p);
for (j=0;jn;j++) pt[j]=p[j];
for (iter=0;;++iter) {
fp=fret;
ibig=0;
del=0.0;
for (i=0;in;i++) {
for (j=0;jn;j++) xit[j]=xi[j][i];
fptt=fret;
linmin(p,xit,fret,func);
if (fptt-fret del) {
del=fptt-fret;
ibig=i+1;
}
}
if (2.0*(fp-fret) = ftol*(fabs(fp)+fabs(fret))+TINY) {
delete []pt;
delete []ptt;
delete []xit;
return true;
}
if (iter == ITMAX)
{
delete []pt;
delete []ptt;
delete []xit;
return false;
//cerr"powell exceeding maximum iterations.";
}
for (j=0;jn;j++) {
ptt[j]=2.0*p[j]-pt[j];
xit[j]=p[j]-pt[j];
pt[j]=p[j];
}
fptt=func(ptt);
if (fptt fp) {
t=2.0*(fp-2.0*fret+fptt)*SQR(fp-fret-del)-del*SQR(fp-fptt);
if (t 0.0) {
linmin(p,xit,fret,func);
for (j=0;jn;j++) {
xi[j][ibig-1]=xi[j][n-1];
xi[j][n-1]=xit[j];
}
}
}
}
}
#endif
#includestdio.h
void main()
{
int x,y,z,c,o,p,q,max;float m,n;
x=0;y=0;z=0;
max=0;
for(x=0;x201;x++)
{
for(y=0;y251;y++)///////////這兒寫錯了for(y=0;x251;y++)
{
for(z=0;z101;z++)
{
m=x+1.5*y+4*z;
n=2*x+1.2*y+z;
if(m=2000n=1000)
c=10*x+12*y+14*z;
if(maxc)
{
max=c;o=x;p=y;q=z;
}
}
}
}
printf("max=%d,x=%d,y=%d,z=%d",c,o,p,q);
}
#include stdio.h
void main ()
{
int num,i;
float x,y,l,m,n,p,a,b;
i=1;
l=0.0;
m=0.0;
n=0.0;
p=0.0;
printf ("請輸入你想計算的x,y的個數(shù):");
scanf("%d",num);
if (num=1)
{
while (i=num);
{
printf("請輸入x的值");
scanf ("%lf",x);
printf("請輸入y的值");
scanf ("%lf",y);
l+=x;
m+=y;
n+=x*y;
p+=x*x;
i++;
}
a=(num*n-l*m)/(num*p-l*l);
b=(p*m-n*l)/(num*p-l*l);
printf("最小二乘法所算得的斜率和截距分別為%f和%f\n",a,b);
}
else printf("mun"輸入有誤!);
}
一個非常簡單的遺傳算法源代碼,是由Denis Cormier (North Carolina State University)開發(fā)的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代碼保證盡可能少,實際上也不必查錯。對一特定的應用修正此代碼,用戶只需改變常數(shù)的定義并且定義“評價函數(shù)”即可。注意代碼的設計是求最大值,其中的目標函數(shù)只能取正值;且函數(shù)值和個體的適應值之間沒有區(qū)別。該系統(tǒng)使用比率選擇、精華模型、單點雜交和均勻變異。如果用Gaussian變異替換均勻變異,可能得到更好的效果。代碼沒有任何圖形,甚至也沒有屏幕輸出,主要是保證在平臺之間的高可移植性。讀者可以從,目錄 coe/evol中的文件prog.c中獲得。要求輸入的文件應該命名為‘gadata.txt’;系統(tǒng)產(chǎn)生的輸出文件為‘galog.txt’。輸入的文件由幾行組成:數(shù)目對應于變量數(shù)。且每一行提供次序——對應于變量的上下界。如第一行為第一個變量提供上下界,第二行為第二個變量提供上下界,等等。
/**************************************************************************/
/* This is a simple genetic algorithm implementation where the */
/* evaluation function takes positive values only and the */
/* fitness of an individual is the same as the value of the */
/* objective function */
/**************************************************************************/
#include stdio.h
#include stdlib.h
#include math.h
/* Change any of these parameters to match your needs */
#define POPSIZE 50 /* population size */
#define MAXGENS 1000 /* max. number of generations */
#define NVARS 3 /* no. of problem variables */
#define PXOVER 0.8 /* probability of crossover */
#define PMUTATION 0.15 /* probability of mutation */
#define TRUE 1
#define FALSE 0
int generation; /* current generation no. */
int cur_best; /* best individual */
FILE *galog; /* an output file */
struct genotype /* genotype (GT), a member of the population */
{
double gene[NVARS]; /* a string of variables */
double fitness; /* GT's fitness */
double upper[NVARS]; /* GT's variables upper bound */
double lower[NVARS]; /* GT's variables lower bound */
double rfitness; /* relative fitness */
double cfitness; /* cumulative fitness */
};
struct genotype population[POPSIZE+1]; /* population */
struct genotype newpopulation[POPSIZE+1]; /* new population; */
/* replaces the */
/* old generation */
/* Declaration of procedures used by this genetic algorithm */
void initialize(void);
double randval(double, double);
void evaluate(void);
void keep_the_best(void);
void elitist(void);
void select(void);
void crossover(void);
void Xover(int,int);
void swap(double *, double *);
void mutate(void);
void report(void);
/***************************************************************/
/* Initialization function: Initializes the values of genes */
/* within the variables bounds. It also initializes (to zero) */
/* all fitness values for each member of the population. It */
/* reads upper and lower bounds of each variable from the */
/* input file `gadata.txt'. It randomly generates values */
/* between these bounds for each gene of each genotype in the */
/* population. The format of the input file `gadata.txt' is */
/* var1_lower_bound var1_upper bound */
/* var2_lower_bound var2_upper bound ... */
/***************************************************************/
void initialize(void)
{
FILE *infile;
int i, j;
double lbound, ubound;
if ((infile = fopen("gadata.txt","r"))==NULL)
{
fprintf(galog,"\nCannot open input file!\n");
exit(1);
}
/* initialize variables within the bounds */
for (i = 0; i NVARS; i++)
{
fscanf(infile, "%lf",lbound);
fscanf(infile, "%lf",ubound);
for (j = 0; j POPSIZE; j++)
{
population[j].fitness = 0;
population[j].rfitness = 0;
population[j].cfitness = 0;
population[j].lower[i] = lbound;
population[j].upper[i]= ubound;
population[j].gene[i] = randval(population[j].lower[i],
population[j].upper[i]);
}
}
fclose(infile);
}
/***********************************************************/
/* Random value generator: Generates a value within bounds */
/***********************************************************/
double randval(double low, double high)
{
double val;
val = ((double)(rand()%1000)/1000.0)*(high - low) + low;
return(val);
}
/*************************************************************/
/* Evaluation function: This takes a user defined function. */
/* Each time this is changed, the code has to be recompiled. */
/* The current function is: x[1]^2-x[1]*x[2]+x[3] */
/*************************************************************/
void evaluate(void)
{
int mem;
int i;
double x[NVARS+1];
for (mem = 0; mem POPSIZE; mem++)
{
for (i = 0; i NVARS; i++)
x[i+1] = population[mem].gene[i];
population[mem].fitness = (x[1]*x[1]) - (x[1]*x[2]) + x[3];
}
}
/***************************************************************/
/* Keep_the_best function: This function keeps track of the */
/* best member of the population. Note that the last entry in */
/* the array Population holds a copy of the best individual */
/***************************************************************/
void keep_the_best()
{
int mem;
int i;
cur_best = 0; /* stores the index of the best individual */
for (mem = 0; mem POPSIZE; mem++)
{
if (population[mem].fitness population[POPSIZE].fitness)
{
cur_best = mem;
population[POPSIZE].fitness = population[mem].fitness;
}
}
/* once the best member in the population is found, copy the genes */
for (i = 0; i NVARS; i++)
population[POPSIZE].gene[i] = population[cur_best].gene[i];
}
/****************************************************************/
/* Elitist function: The best member of the previous generation */
/* is stored as the last in the array. If the best member of */
/* the current generation is worse then the best member of the */
/* previous generation, the latter one would replace the worst */
/* member of the current population */
/****************************************************************/
void elitist()
{
int i;
double best, worst; /* best and worst fitness values */
int best_mem, worst_mem; /* indexes of the best and worst member */
best = population[0].fitness;
worst = population[0].fitness;
for (i = 0; i POPSIZE - 1; ++i)
{
if(population[i].fitness population[i+1].fitness)
{
if (population[i].fitness = best)
{
best = population[i].fitness;
best_mem = i;
}
if (population[i+1].fitness = worst)
{
worst = population[i+1].fitness;
worst_mem = i + 1;
}
}
else
{
if (population[i].fitness = worst)
{
worst = population[i].fitness;
worst_mem = i;
}
if (population[i+1].fitness = best)
{
best = population[i+1].fitness;
best_mem = i + 1;
}
}
}
/* if best individual from the new population is better than */
/* the best individual from the previous population, then */
/* copy the best from the new population; else replace the */
/* worst individual from the current population with the */
/* best one from the previous generation */
if (best = population[POPSIZE].fitness)
{
for (i = 0; i NVARS; i++)
population[POPSIZE].gene[i] = population[best_mem].gene[i];
population[POPSIZE].fitness = population[best_mem].fitness;
}
else
{
for (i = 0; i NVARS; i++)
population[worst_mem].gene[i] = population[POPSIZE].gene[i];
population[worst_mem].fitness = population[POPSIZE].fitness;
}
}
/**************************************************************/
/* Selection function: Standard proportional selection for */
/* maximization problems incorporating elitist model - makes */
/* sure that the best member survives */
/**************************************************************/
void select(void)
{
int mem, i, j, k;
double sum = 0;
double p;
/* find total fitness of the population */
for (mem = 0; mem POPSIZE; mem++)
{
sum += population[mem].fitness;
}
/* calculate relative fitness */
for (mem = 0; mem POPSIZE; mem++)
{
population[mem].rfitness = population[mem].fitness/sum;
}
population[0].cfitness = population[0].rfitness;
/* calculate cumulative fitness */
for (mem = 1; mem POPSIZE; mem++)
{
population[mem].cfitness = population[mem-1].cfitness +
population[mem].rfitness;
}
/* finally select survivors using cumulative fitness. */
for (i = 0; i POPSIZE; i++)
{
p = rand()%1000/1000.0;
if (p population[0].cfitness)
newpopulation[i] = population[0];
else
{
for (j = 0; j POPSIZE;j++)
if (p = population[j].cfitness
ppopulation[j+1].cfitness)
newpopulation[i] = population[j+1];
}
}
/* once a new population is created, copy it back */
for (i = 0; i POPSIZE; i++)
population[i] = newpopulation[i];
}
/***************************************************************/
/* Crossover selection: selects two parents that take part in */
/* the crossover. Implements a single point crossover */
/***************************************************************/
void crossover(void)
{
int i, mem, one;
int first = 0; /* count of the number of members chosen */
double x;
for (mem = 0; mem POPSIZE; ++mem)
{
x = rand()%1000/1000.0;
if (x PXOVER)
{
++first;
if (first % 2 == 0)
Xover(one, mem);
else
one = mem;
}
}
}
/**************************************************************/
/* Crossover: performs crossover of the two selected parents. */
/**************************************************************/
void Xover(int one, int two)
{
int i;
int point; /* crossover point */
/* select crossover point */
if(NVARS 1)
{
if(NVARS == 2)
point = 1;
else
point = (rand() % (NVARS - 1)) + 1;
for (i = 0; i point; i++)
swap(population[one].gene[i], population[two].gene[i]);
}
}
/*************************************************************/
/* Swap: A swap procedure that helps in swapping 2 variables */
/*************************************************************/
void swap(double *x, double *y)
{
double temp;
temp = *x;
*x = *y;
*y = temp;
}
/**************************************************************/
/* Mutation: Random uniform mutation. A variable selected for */
/* mutation is replaced by a random value between lower and */
/* upper bounds of this variable */
/**************************************************************/
void mutate(void)
{
int i, j;
double lbound, hbound;
double x;
for (i = 0; i POPSIZE; i++)
for (j = 0; j NVARS; j++)
{
x = rand()%1000/1000.0;
if (x PMUTATION)
{
/* find the bounds on the variable to be mutated */
lbound = population[i].lower[j];
hbound = population[i].upper[j];
population[i].gene[j] = randval(lbound, hbound);
}
}
}
/***************************************************************/
/* Report function: Reports progress of the simulation. Data */
/* dumped into the output file are separated by commas */
/***************************************************************/
。。。。。
代碼太多 你到下面呢個網(wǎng)站看看吧
void main(void)
{
int i;
if ((galog = fopen("galog.txt","w"))==NULL)
{
exit(1);
}
generation = 0;
fprintf(galog, "\n generation best average standard \n");
fprintf(galog, " number value fitness deviation \n");
initialize();
evaluate();
keep_the_best();
while(generationMAXGENS)
{
generation++;
select();
crossover();
mutate();
report();
evaluate();
elitist();
}
fprintf(galog,"\n\n Simulation completed\n");
fprintf(galog,"\n Best member: \n");
for (i = 0; i NVARS; i++)
{
fprintf (galog,"\n var(%d) = %3.3f",i,population[POPSIZE].gene[i]);
}
fprintf(galog,"\n\n Best fitness = %3.3f",population[POPSIZE].fitness);
fclose(galog);
printf("Success\n");
}
我也在學這個課,老兄。我編的這個用于解決二次的問題。輸入目標函數(shù)系數(shù)和初始區(qū)間及熟練精度。 黃金分割法:
# include stdio.h
# include math.h
float d,e,f;
void main ()
{printf("請輸入目標函數(shù)的二次項,一次項,常數(shù)項,中間用空格分開\n");
scanf("%f %f %f",d,e,f);
float fox (float x);
float a0,b0,z,a,b,x1,x2,f1,f2,xx;
char k,m;
int n;
printf("請輸入初始區(qū)間a0,b0,收斂精度z,中間用空格分開\n");
scanf("%f %f %f",a,b,z);
a=a0;
b=b0;
x1=a+0.382*(b-a);
f1=fox(x1);
x2=a+0.618*(b-a);
f2=fox(x2);
if(f1f2) {n=0;
b=x2;
x2=x1;
f2=f1;
}
else {n=1;
a=x1;
x1=x2;
f1=f2;
}
while(fabs((b-a))z)
{if(n==0) {x1=a+0.382*(b-a);
f1=fox(x1);
}
else {x2=a+0.618*(b-a);
f2=fox(x2);
}
}
if(f1f2) {n=0;
b=x2;
x2=x1;
f2=f1;
}
else {n=1;
a=x1;
x1=x2;
f1=f2;
}
xx=(a+b)/2;
printf("極小點和極小值xx=%f,ff=%f\n",xx,fox(xx));
k=getchar();
m=getchar();
}
float fox(float x)
{float r;
r=d*x*x+e*x+f;
return(r);
}