|
楼主 |
发表于 2004-5-15 07:50:13
|
显示全部楼层
< center" align=center>/*最优梯度法求多元函数的极小值 TIDU.C */<p></p></P><>#include<conio.h></P><>#include<math.h></P><P>#include<stdio.h></P><P>#define N 2</P><P>int j; double x[N];</P><P>double f(double x[])</P><P>{</P><P>double fxy;</P><P>fxy=x[0]-x[1]+2.0*x[0]*x[0]+2.0*x[0]*x[1]+x[1]*x[1]+log(1.0+x[1]*x[1]);</P><P>return(fxy);</P><P>}</P><P>void grad(double x[],double g[])</P><P> {</P><P> g[0]=4.0*x[0]+2.0*x[1]+1.0;</P><P> g[1]=2.0*x[0]+2.0*x[1]-1.0+2.0*x[1]/(1.0+x[1]*x[1]);</P><P> }</P><P>double fun(double x[],double g[],double lbt)</P><P>{</P><P>int i; double x2[N];</P><P>for(i=0;i<N;i++) x2=x-lbt*g;</P><P>return(f(x2));</P><P>}</P><P>double ca_min(double x[],double g[],double eps)</P><P>{</P><P>double a,b,c,x1,x2,x3,f1,f2,f3;</P><P>a=-2.0; b=2.0; c=(b-a)*0.25; x1=a+c; f1=fun(x,g,x1);</P><P>x2=x1+c; f2=fun(x,g,x2); x3=x2+c; f3=fun(x,g,x3);</P><P>for(;;)</P><P> {</P><P> if(f1<=f2&&f1<f3)</P><P> { b=x2;x2=x1;f2=f1; }</P><P> else if(f3<=f2&&f3<f1)</P><P> { a=x2;x2=x3;f2=f3; }</P><P> else</P><P> { a=x1;b=x3; }</P><P> c=(b-a)*0.25;</P><P> if(fabs(c)<eps)break;</P><P> x1=a+c;f1=fun(x,g,x1); x3=x2+c;f3=fun(x,g,x3);</P><P> }</P><P>return(x2);</P><P>}</P><P> <p></p></P><P>void tidufa(double x0[],double eps)</P><P>{</P><P>int i; unsigned k=0;</P><P>double lbt,f1,f2,x1[N],g[N];</P><P>f1=f(x0);</P><P>while(k<100)</P><P> {</P><P> grad(x0,g);</P><P> lbt=ca_min(x0,g,eps*0.1);</P><P> /*printf("\nlbt=%g \n",lbt);*/</P><P> for(i=0;i<N;i++)x1=x0-lbt*g;</P><P> f2=f(x1);</P><P> for(i=0;i<N;i++)x0=x1;</P><P> if(fabs(f2-f1)<eps)</P><P> {</P><P> printf("f2-f1<eps k=%d",k);</P><P> break;</P><P> }</P><P> /*printf("k=%d x1=%15.14lf x2=%15.14lf",k,x1[0],x1[1]);*/</P><P> f1=f2;k++;</P><P> }</P><P>}</P><P> <p></p></P><P>main()</P><P>{</P><P>int i;</P><P>double x0[N],eps=1.0e-015;</P><P>x0[0]=1.0;x0[1]=2.0;</P><P>tidufa(x0,eps);</P><P> for(i=0;i<N;i++)</P><P 21.6pt">printf("\nx[%d] = %12.10lf ",i,x0);</P><P>printf("\nf(X) = %12.10lf ",f(x0);</P><P>}</P><P> <p></p></P> |
|