反反复复二分法:
#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;
y1=f(x1);
y2=f(x2);
while(fabs(y1-y2)>=E)
{
if(y1>y2)
{ a=x1;
x1=x2;
y1=y2;
x2=a+H*(b-a);
y2=f(x2);
}
else { b=x2;
x2=x1;
y2=y1;
x1=a+(1-H)*(b-a);
y1=f(x1);
}
}
return (x1+x2)/2;
}
float f(float x)
{return x*x-6*x+2;}
进退法:
#include
#include"math.h"
void main()
{
float x0,h,x1,jintui(float x0, float h);
printf("Enter x0,h:\n");
scanf("%f,%f",&x0,&h);
x1=jintui(x0, h);
printf("(%f,%f)\n",x0,x1);
}
float jintui(float x0,float h)
{
float f(float x),x1,march(float x0,float h);
if(f(x0)>f(x0+h))
{ x1=march(x0,h);}
else{ h=-h;
x1=march(x0,h);
}
return x1;
}