#include<math.h> #include<stdio.h> # define eps 0.01 double f (double coe[], double x[]) //返回待求函数的函数值 { return coe[0]*pow(x[0],2)+coe[1]*pow(x[1],2)+coe[2]*x[0]*x[1]+coe[3]*x[0]+coe[4]*x[1]+coe[5]; } void grads (double coe[], double x[],double grads_x[]) //求解函数的梯度 { grads_x[0] = 2*coe[0]*x[0]+coe[2]*x[1]+coe[3]; grads_x[1] = 2*coe[1]*x[1]+coe[2]*x[0]+coe[4]; } void H (double coe[], double h[])//求解海赛矩阵 { h[0] = 2.0*coe[0]; h[1] = coe[2]; h[2] = coe[2]; h[3] = 2.0*coe[1]; } void inverseH (double h[], double inverseh[])//求解海赛矩阵的逆矩阵 { double deter; deter = h[0]*h[3]-h[1]*h[2]; inverseh[0] = h[3]/deter; inverseh[1] = -h[1]/deter; inverseh[2] = -h[2]/deter; inverseh[3] = h[0]/deter; } void main()//主函数 { double coe[6] = {1,2,-2,-4,0,0}, x[2] = {1 , 1}, grads_x[2], h[4], inverseh[4], fx = 0; grads(coe, x, grads_x);//求梯度 while(sqrt(pow(grads_x[0],2)+pow(grads_x[1],2))-eps>0) { H(coe, h);//求海赛矩阵 inverseH(h, inverseh);//海赛矩阵求逆 x[0] = x[0]-(inverseh[0]*grads_x[0]+inverseh[1]*grads_x[1]); x[1] = x[1]-(inverseh[2]*grads_x[0]+inverseh[3]*grads_x[1]); grads(coe, x, grads_x); } fx = f(coe, x); printf("最优解为:"); for(int i=0;i<2;i++) { printf("\n%f\n",x[i]); } printf("\n最优值为:"); printf("\nfx=%f \n",fx); }
- 粉丝: 0
- 资源: 1
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助