这是迭代算法的小应用,相关的理论请参考相关书籍,我这里只给出关键的函数及主程序段,其余相关的细节就不再一一罗列了.
#include "Iterator.h"
#include "MyAssert.h"
#include "Ulti.h"
#include <stdlib.h>
#include <stdio.h>
void f0_618(Type a0,Type b0,Type e,Type (*arguF)(Type),FILE* outputFile)
{
Type a,b;//the bordern value.
Type lamda,miu;
Type flamda,fmiu;
int iteratorNum=0;
assertF(b0>=a0,"in f0_618 b0<a0");
assertF(arguF!=NULL,"in f0_618 arguF is NULL");
assertF(outputFile!=NULL,"in f0_618 outputFile is NULL");
a=a0;
b=b0;
lamda=a+(1-CFI0_618)*(b-a);
miu=a+CFI0_618*(b-a);
flamda=(*arguF)(lamda);
fmiu=(*arguF)(miu);
while((b-a)>e)
{
if(flamda>=fmiu)
{
a=lamda;
b=b;
lamda=miu;
flamda=fmiu;
miu=a+CFI0_618*(b-a);
fmiu=(*arguF)(miu);
}
else
{
a=a;
b=miu;
miu=lamda;
fmiu=flamda;
lamda=a+(1-CFI0_618)*(b-a);
flamda=(*arguF)(lamda);
}
iteratorNum++;
fprintf(outputFile,"a:%-12f b:%-12f lamda:%-12f miu:%-12f flamda:%-12f fmiu:%-12f\r\n",a,b,lamda,miu,flamda,fmiu);
}
/*adjust for output*/
if(b<a)swap(&a,&b);
fprintf(outputFile,"total iterator time is:%d\r\n",iteratorNum);
fprintf(outputFile,"x is now between :[%f,%f]\r\n",a,b);
fprintf(outputFile,"the best answer is about in:%f,its mapped f value is:%f\r\n",(a+b)/2,(*arguF)((a+b)/2));
}
/*Test Program*/
#include "MyAssert.h"
#include "FindRoot.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Type testF(Type argu);
char *inFileName="inputData.txt";
/*
input data specification
x1,x2 means the root is located about in [x1,x2]
*/
char *outFileName="outputData.txt";
#define DEBUG 0
void main(int argc,char* argv[])
{
FILE *inputFile;/*input file*/
FILE *outputFile;/*output file*/
double startTime,endTime,tweenTime;/*time callopsed info*/
float a,b;
/*input file open*/
if(argc>1)strcpy(inFileName,argv[1]);
assertF((inputFile=fopen(inFileName,"rb"))!=NULL,"input file error");
printf("input file open success\n");
/*outpout file open*/
if(argc>2)strcpy(outFileName,argv[2]);
assertF((outputFile=fopen(outFileName,"wb"))!=NULL,"output file error");
printf("output file open success\n");
/*Read info data*/
fscanf(inputFile,"%f,%f",&a,&b);
printf("read in data info:%f,%f\n",a,b);
#if DEBUG
printf("\n*******start of test program******\n");
printf("now is runnig,please wait...\n");
startTime=(double)clock()/(double)CLOCKS_PER_SEC;
/******************Core program code*************/
f0_618(a,b,0.001,&testF,outputFile);
/******************End of Core program**********/
endTime=(double)clock()/(double)CLOCKS_PER_SEC;
tweenTime=endTime-startTime;/*Get the time collapsed*/
/*Time collapsed output*/
printf("the collapsed time in this algorithm implement is:%f\n",tweenTime);
fprintf(outputFile,"the collapsed time in this algorithm implement is:%f\r\n",tweenTime);
printf("\n*******end of test program******\n");
#endif
printf("program end successfully,\n you have to preess any key to clean the buffer area to output,otherwise,you wiil not get the total answer.\n");
getchar();/*Screen Delay Control*/
return;
}
Type testF(Type x)
{
return x*x*x-5*x*x+16*x-80;
}