最优化技术之黄金分割法

 这是我所学的专业的一门课程《最优化设计》中的黄金分割法。

#include <stdio.h>
#include <math.h>
#define e 0.001
#define tt 0.01
float f(double x)
{
float y=pow(x,4)-4*pow(x,3)-6*pow(x,2)-16*x+4;
return(y);
}
finding(float *p1,float*p2)
{
float x1=0,x2,x3,t,f1,f2,f3,h=tt;
int n=0;
x2=x1+h;f1=f(x1);f2=f(x2);
if(f2>f1) {h=-h;t=x2;x2=x1;x1=t;}
do
{ x3=x2+h;h=2*h;f3=f(x3);n=n+1;}
while(f3<f2);
if(x1>x3) {t=x1;x1=x3;x3=t;}
*p1=x1;*p2=x3;
return(n);
}
gold(float *p)
{
float a,b,x1,x2,f1,f2;
int n=0;
finding(&a,&b);
do
{x1=a+0.382*(b-a);
x2=a+0.618*(b-a);f1=f(x1);f2=f(x2);n=n+1;
if(f1>f2) a=x1;
else b=x2;}
while((b-a)>e);
*p=(x1+x2)/2;return(n);
}
void main()
{
float a,b,x,min;int n1,n2;
n1=finding(&a,&b);
n2=gold(&x);
min=f(x);
printf("\n The area is %f to %f.",a,b);
printf("\n The nunmber 1 is %d.",n1);
printf("\n The min is %f and the result is %f.",x,min);
printf("\n The nunmber 2 is %d.",n2);
}
 

下载cpp文件

 

 

    已经有5条评论