反反复复二分法:
#include
#include"math.h"
#define E 0.01
void main()
{ float a,b,x,erfen(float a,float b); printf("Enter a,b\n");
scanf("%f,%f",&a,&b);
x=erfen(a,b);
printf("x=%f\n",x);
}
float erfen(float a,float b)
{
float c,df(float x);
while (fabs(a-b)>E)
{
c=(a+b)/2;
if(df(c)==0) break;
else { if(df(a)*df(c)<0) b=c;
else a=c;
}
}
return c;
}
float df(float x)
{return 2*x-6;}
黄金分割法:
#include
#include"math.h"
#define E 0.001
#define H 0.618
void main()
{ float a,b,x;
float goldcut(float a,float b);
printf("Enter a,b\n");
scanf("%f,%f",&a,&b);
x=goldcut(a,b);
printf("x*=%f\n",x);
}
float goldcut(float a,float b) { float x1,x2,y1,y2;
float f(float x);
x2=a+H*(b-a);
x1=a+b-x2;