⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tidu.cpp

📁 用C++编的求多元函数梯度方法
💻 CPP
字号:
#include "iostream.h"
#include "math.h"
void compute_grad(double (*pf)(double *x),int n,double *point,double *grad);
double fun(double *x);

void main(void)
{
int n=2;
double x[2]={1,0.5};
double grad[2];
compute_grad(fun,n,x,grad);
cout<<"grad[1]="<<grad[0]<<"\n";
cout<<"grad[2]="<<grad[1]<<"\n";
}

void compute_grad(double(*pf)(double *x),int n,double *point,double *grad)
{
double h=1e-3;
int i;
double *temp=new double[n];
for(i=1;i<=n;i++)
   temp[i-1]=point[i-1];
for (i=1;i<=n;i++)
{
temp[i-1]+=0.5*h;
grad[i-1]=4*pf(temp)/(3*h);
temp[i-1]-=h;
grad[i-1]-=(4*pf(temp)/(3*h));
temp[i-1]+=(3*h/2);
grad[i-1]-=(pf(temp)/(6*h));
temp[i-1]-=(2*h);
grad[i-1]+=(pf(temp)/(6*h));
temp[i-1]=point[i-1];
}
delete[] temp;
}

double fun(double *x)
{
return 100*(x[1]-x[0]*x[0])*(x[1]-x[0]*x[0])+(1-x[0])*(1-x[0]);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -