📄 tidu.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 + -