當前位置:首頁 » 編程語言 » C語言如何求解梯度
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

C語言如何求解梯度

發布時間: 2023-01-18 00:39:27

Ⅰ 求c語言 用梯形法求定積分(數值求解演算法)

#include<stdio.h>
float f(float x)
{
return x*x+2*x+1;
}
void main()
{
float a,b,len,F=0;//
int n,i;
printf("Please input a,b: ");
scanf("%f%f",&a,&b);
printf("Please input n: ");
scanf("%d",&n);
len=(a+b)/n;//區間長度
for(i=0;i<n;i++)
{
F+=len*f(a);
a+=len;
}
printf("%f\n",F);
}
結果例如:
Please input a,b: 0 10.0
Please input n: 100
437.349792

Ⅱ 用C語言編程歐拉法、梯形法、二級二階R-K、三級三階R-K、四級四階R-K求解下列方程的數值解

歐拉法求解y'=-2y-4x, x0=0, y0=2, x<=1的求解如下:

#include<stdio.h>

/*solve ode: dy/dx = -2*y -4*x*/

float fun(float x,float y){

float f;

f=-2.0*y -4.0*x;

return f;

}

int main(){

float x0=0,y0=2.0,x,y,h=0.1,t=1.0,k;

/* printf(" Enter x0,y0,h,xn: "); scanf("%f%f%f%f",&x0,&y0,&h,&t);*/

x=x0;

y=y0;

printf(" x y ");

while(x<=t) {

k=h*fun(x,y);

y=y+k;

x=x+h;

printf("%0.3f %0.3f ",x,y);

}return 0;

}

代碼截圖+運行結果

(晚點我再來看後面的幾小問)

Ⅲ C語言實慣用梯形法或辛普森法求解定積分的值

//梯形法求定積分
#include<stdio.h>
#include<math.h>
//定義被積函數
double func(double x){
return sin(x)*cos(x);
}

void main(){
double a,b,h,x,sum;
int i,n;
printf("Input a b and n: ");
scanf("%lf%lf%d",&a,&b,&n);
h=(b-a)/n;
x=a;
sum=(func(a)+func(b))/2;
for(i=1; i<n; i++){
x += h;
sum += func(x);
}
sum *= h;
printf("sum=%.4lf\n",sum);
}

Ⅳ 機械優化設計 變尺度法 c語言程序

計算 f(x1,x2)=x1^2+2*x2^2-4*x1-2*x1*x2 的無約束極值,初始點x0=[1,1]。

/*
tt ---- 一維搜索初始步長
ff ---- 差分法求梯度時的步長
ac ---- 終止迭代收斂精度
ad ---- 一維搜索收斂精度
n ----- 設計變數的維數
xk[n] -- 迭代初始點
*/

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>

#define tt 0.01
#define ff 1.0e-6
#define ac 1.0e-6
#define ad 1.0e-6
#define n 2

double ia;

double fny(double *x)
{
double x1=x[0],x2=x[1];

double f;
f=x1*x1+2*x2*x2-4*x1-2*x1*x2;

return f;
}

double * iterate(double *x,double a,double *s)
{
double *x1;
int i;
x1=(double *)malloc(n*sizeof(double));
for(i=0;i<n;i++)
x1[i]=x[i]+a*s[i];
return x1;
}

double func(double *x,double a,double *s)
{
double *x1;
double f;
x1=iterate(x,a,s);
f=fny(x1);
return f;
}

void finding(double a[3],double f[3],double *xk,double *s)
{
double t=tt;
int i;
double a1,f1;
a[0]=0;f[0]=func(xk,a[0],s);
for(i=0;;i++)
{
a[1]=a[0]+t;
f[1]=func(xk,a[1],s);
if(f[1]<f[0]) break;
if(fabs(f[1]-f[0])>=ad)
{
t=-t;
a[0]=a[1];f[0]=f[1];
}
else
{
if(ia==1) return; //break
t=t/2;ia=1;
}
}

for(i=0;;i++)
{
a[2]=a[1]+t;
f[2]=func(xk,a[2],s);
if(f[2]>f[1]) break;
t=2*t;
a[0]=a[1];f[0]=f[1];
a[1]=a[2];f[1]=f[2];
}
if(a[0]>a[2])
{
a1=a[0];
f1=f[0];
a[0]=a[2];
f[0]=f[2];
a[2]=a1;
f[2]=f1;
}
return;
}

double lagrange(double *xk,double *ft,double *s)
{
int i;
double a[3],f[3];
double b,c,d,aa;
finding(a,f,xk,s);
for(i=0;;i++)
{
if(ia==1) { aa=a[1]; *ft=f[1]; break; }

d=(pow(a[0],2)-pow(a[2],2))*(a[0]-a[1])-(pow(a[0],2)-pow(a[1],2))*(a[0]-a[2]);
if(fabs(d)==0) break;

c=((f[0]-f[2])*(a[0]-a[1])-(f[0]-f[1])*(a[0]-a[2]))/d;
if(fabs(c)==0) break;

b=((f[0]-f[1])-c*(pow(a[0],2)-pow(a[1],2)))/(a[0]-a[1]);
aa=-b/(2*c);
*ft=func(xk,aa,s);
if(fabs(aa-a[1])<=ad) {if(*ft>f[1]) aa=a[1];break;}
if(aa>a[1])
{
if(*ft>f[1]) {a[2]=aa;f[2]=*ft;}
else if(*ft<f[1]) {a[0]=a[1];a[1]=aa;f[0]=f[1];f[1]=*ft;}
else if(*ft==f[1])
{
a[2]=aa;a[0]=a[1];
f[2]=*ft;f[0]=f[1];
a[1]=(a[0]+a[2])/2;
f[1]=func(xk,a[1],s);
}
}
else
{
if(*ft>f[1]) {a[0]=aa;f[0]=*ft;}
else if(*ft<f[1]) {a[2]=a[1];a[1]=aa;f[2]=f[1];f[1]=*ft;}
else if(*ft==f[1])
{a[0]=aa;a[2]=a[1];
f[0]=*ft;f[2]=f[1];
a[1]=(a[0]+a[2])/2;
f[1]=func(xk,a[1],s);
}
}

}
if(*ft>f[1]) {*ft=f[1];aa=a[1];}
return aa;
}

double *gradient(double *xk)
{
double *g,f1,f2,q;
int i;
g=(double*)malloc(n*sizeof(double));
f1=fny(xk);
for(i=0;i<n;i++)
{q=ff;
xk[i]=xk[i]+q; f2=fny(xk);
g[i]=(f2-f1)/q; xk[i]=xk[i]-q;
}
return g;
}

double * bfgs(double *xk)
{
double u[n],v[n],h[n][n],dx[n],dg[n],s[n];
double aa,ib;
double *ft,*xk1,*g1,*g2,*xx,*x0=xk;
double fi;
int i,j,k;

ft=(double *)malloc(sizeof(double));
xk1=(double *)malloc(n*sizeof(double));

for(i=0;i<n;i++)
{
s[i]=0;
for(j=0;j<n;j++)
{
h[i][j]=0;
if(j==i) h[i][j]=1;
}
}
g1=gradient(xk);
fi=fny(xk);
x0=xk;

for(k=0;k<n;k++)
{
ib=0;
if(ia==1) { xx=xk; break; }
ib=0;
for(i=0;i<n;i++) s[i]=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
s[i]+= -h[i][j]*g1[j];
aa=lagrange(xk,ft,s);
xk1=iterate(xk,aa,s);
g2=gradient(xk1);

for(i=0;i<n;i++)
if((fabs(g2[i])>=ac)&&(fabs(g2[i]-g1[i])>=ac))
{ib=ib+1;}
if(ib==0) { xx=xk1; break; }
fi=*ft;
if(k==n-1)
{ int j;
xk=xk1;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
h[i][j]=0;
if(j==i) h[i][j]=1;
}
g1=g2; k=-1;
}

else
{
int j;
double a1=0,a2=0;
for(i=0;i<n;i++)
{
dg[i]=g2[i]-g1[i];
dx[i]=xk1[i]-xk[i];
}

for(i=0;i<n;i++)
{
int j;
u[i]=0;v[i]=0;
for(j=0;j<n;j++)
{
u[i]=u[i]+dg[j]*h[j][i];
v[i]=v[i]+dg[j]*h[i][j];
}
}

for(j=0;j<n;j++)
{
a1+=dx[j]*dg[j];
a2+=v[j]*dg[j];
}
if(fabs(a1)!=0)
{
a2=1+a2/a1;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
h[i][j]+=(a2*dx[i]*dx[j]-v[i]*dx[j]-dx[i]*u[j])/a1;
}
xk=xk1; g1=g2;
}
}
if(*ft>fi) { *ft=fi; xx=xk;}
xk=x0;
return xx;
}

void main ()
{

int k;
double *xx,f;
double xk[n]={1,1};
xx=bfgs(xk);
f=fny(xx);
printf("\n\nThe Optimal Design Result Is:\n");
for(k=0;k<n;k++)
{printf("\n\tx[%d]*=%f",k+1,xx[k]);}
printf("\n\tf*=%f",f);
getch();
}

這是基於一本書上的演算法。但我很奇怪,原書中的演算法有結果列出,但是我卻不能通過編譯。真是納悶!修改後可以得到結果了,如果你要使用這個簡單的程序,你只需更改 維數n、double fny(double *x)的實現部分以及main函數中的xk初值就可以了。不過這個程序也不是很好。

Ⅳ 求C語言高手編程

Numerical Recipes in C
一書及所附程序,有完整程序。不過我封裝了它的C++版本,可以對但參數或多參數求極值,完整的頭文件為:

#ifndef __OPTIMIZATION_H__
#define __OPTIMIZATION_H__

//////////////////////////////////////////////////////////////////////////
// class TOptimization
//
// $ 求函數一個或多個參數的最小值
//
// 該類默認對一個參數優化,一般只要輸入優化參數數目
// 優化目標函數就可以使用。
//
// ...主要代碼來自:
// Numerical Recipes in C++
// The Art of Scientific Computing
// Second Edition
// William H. Press Saul A. Teukolsky
// William T. Vetterling Brian P. Flannery
//
// 中譯本:
// C++ 數值演算法(第二版) 胡健偉 趙志勇 薛運華 等譯
// 電子工業出版社 北京 (2005)
//
// Author: Jian Feng
// Email: [email protected]
// Dec. 9, 2006
//
//////////////////////////////////////////////////////////////////////////
//
// 輸入函數:
//
// @MaxIterationStep: 最大迭代次數, 默認 1000
// @ParameterNumbers: 優化參數數目, 默認 1
// @InitMatrix: 初始化矩陣參數(N*N), 默認
// @Tolerance: 容許公差, 默認 1E-7
//
// 執行函數:
//
// @ExecutePowell: 利用powell方法進行多參數優化
// @ExecuteBrent: 利用brent方法進行單參數優化
//
// 輸出函數:
//
// @OptimizatedParameters: 優化結果數據
// @ObjectiveFunctionValue: 目標函數在優化值處的值
//
// 使用示例:
//
// 1. 單參數
// double objfun(double a){
// double sum = 0;
// for(int i = 0; i < DataPoints; ++i)
// sum += SQR(Exps[i] - Theo(a));
// }
// double value
// TOptimization opt;
// if(opt.ExecuteBrent(objfun, -10, -1)) opt.OptimizatedParameters(&value);
//
// 2. 多參數
// double objfun(double *a){
// double sum = 0;
// for(int i = 0; i < DataPoints; ++i)
// sum += SQR(Exps[i] - Theo(a));
// }
// double value[3]
// TOptimization opt(3);
// double ival[3] = {-1, 0, 1};
// if(opt.ExecutePowell(objfun, ival)) opt.OptimizatedParameters(value);
//
namespace{
static int ncom; //公用變數
static double *pcom_p; //公用變數
static double *xicom_p; //公用變數
static double (*nrfunc)(double*); //公用函數指針
}

class TOptimization
{
private:
typedef double (*Reff)(double *);
typedef double (*Ptrf)(double );

public:
TOptimization(int n = 1);
~TOptimization(){ FreeMemory(); }

//主要方法
void ParameterNumbers(int n){ FreeMemory(); num = n; AllocateMemory(); }

//利用powell方法對一個或多個參數優化
bool ExecutePowell(Reff obj, double *a = 0);

//利用brent方法對一個參數優化,需給出參數所在的區間
bool ExecuteBrent(Ptrf obj, double vFrom = 0, double vTo = 1);

void OptimizatedParameters(double *a){ for(int i=0; i<num; ++i) a[i]=coef[i];}

void OptimizatedParameters(double &a){ a = vmin; }

//void OptimizatedParameters(double *a){
// if(method) for(int i=0; i<num; ++i) a[i]=coef[i];
// else *a = vmin;
//}

//其它方法
void InitMatrix(double **m)
{
for(int i=0; i<num; ++i)
for(int j = 0; j<num; ++j)
matx[i][j]=m[i][j];
setm = true;
}

void MaxIterationStep(int s){ ITMAX = s; }

void Tolerance(double eps){ ftol = eps; }

double ObjectiveFunctionValue()const{ return fret; }

private:

double brent(double ax, double bx, double cx, Ptrf f, double tol, double &xmin, int &flag);
void mnbrak(double &ax, double &bx, double &cx, double &fa, double &fb, double &fc, Ptrf func);
void linmin(double *p, double *xi, double &fret, Reff func);
bool powell(double *p, double **xi, double ftol, int &iter, double &fret, Reff func);

void shft2(double &a, double &b, const double c){ a=b; b=c; }

void shft3(double &a, double &b, double &c, const double d){ a=b; b=c; c=d; }

double SQR(double x){ return x * x; }

void SWAP(double &a, double &b){ double m=a; a=b; b=m; }

double SIGN(const double &a, const double &b){return b >= 0?(a>=0?a:-a):(a>=0?-a:a);}

double MAX(const double &a, const double &b){return b > a ? (b) : (a);}

void AllocateMemory();

void FreeMemory();

static double f1dim(double x)
{
int j;
double *xt = new double [ncom];
//Vec_Dp &pcom=*pcom_p,&xicom=*xicom_p;
double *pcom = pcom_p, *xicom = xicom_p;
for (j=0;j<ncom;j++)
xt[j]=pcom[j]+x*xicom[j];
//delete []xt;
double val = nrfunc(xt);
delete []xt;
return val;
}

bool setm; //是否設置優化方向初始矩陣

int num; //優化參數
int ITMAX; //最大迭代數
int iter; //實際迭代步數
int method; //優化方法 0: 1-D brent, 2: M-D Powell

double vmin; //一維優化參數
double ftol; //容許差
double fret; //目標函數值

double *coef; //多維優化參數值
double **matx; //多維優化參數方向的初始值

};

//////////////////////////////////////////////////////////////////////////

inline TOptimization::TOptimization(int n )
{
num = n;
ftol = 1e-7;
ITMAX = 1000;
iter = 0;
fret = 0.;
vmin = 0.;
method = 0;
setm = false;

AllocateMemory();
}

inline void TOptimization::AllocateMemory()
{
pcom_p = new double [num];
xicom_p = new double [num];
coef = new double [num];
matx = new double *[num];
for(int i = 0; i < num; ++i)
{
coef[i] = 0.;
matx[i] = new double [num];
for(int j = 0; j < num; ++j)
matx[i][j]=(i == j ? 1.0 : 0.0);
}
}

inline void TOptimization::FreeMemory()
{
for(int i = 0; i < num; ++i)
{
delete []matx[i];
}
delete []matx;
delete []pcom_p;
delete []xicom_p;
delete []coef;
}

inline bool TOptimization::ExecutePowell(Reff obj, double *a)
{
method = 1;
if(a)
for(int i = 0; i < num; ++i) coef[i] = a[i];
return powell(coef, matx, ftol, iter, fret, obj);
}

inline bool TOptimization::ExecuteBrent(Ptrf obj, double vFrom, double vTo)
{
method = 0;
int flag;
double cx, fa, fb, fc;
mnbrak(vFrom,vTo,cx,fa,fb,fc,obj);
fret = brent(vFrom,vTo,cx,obj, ftol,vmin, flag);
return flag ? true : false;
}

inline void TOptimization::mnbrak(double &ax, double &bx, double &cx, double &fa,
double &fb, double &fc, Ptrf func)
{
const double GOLD=1.618034,GLIMIT=100.0,TINY=1.0e-20;
double ulim,u,r,q,fu;

fa=func(ax);
fb=func(bx);
if (fb > fa) {
SWAP(ax,bx);
SWAP(fb,fa);
}
cx=bx+GOLD*(bx-ax);
fc=func(cx);
while (fb > fc) {
r=(bx-ax)*(fb-fc);
q=(bx-cx)*(fb-fa);
u=bx-((bx-cx)*q-(bx-ax)*r)/
(2.0*SIGN(MAX(fabs(q-r),TINY),q-r));
ulim=bx+GLIMIT*(cx-bx);
if ((bx-u)*(u-cx) > 0.0) {
fu=func(u);
if (fu < fc) {
ax=bx;
bx=u;
fa=fb;
fb=fu;
return;
} else if (fu > fb) {
cx=u;
fc=fu;
return;
}
u=cx+GOLD*(cx-bx);
fu=func(u);
} else if ((cx-u)*(u-ulim) > 0.0) {
fu=func(u);
if (fu < fc) {
shft3(bx,cx,u,cx+GOLD*(cx-bx));
shft3(fb,fc,fu,func(u));
}
} else if ((u-ulim)*(ulim-cx) >= 0.0) {
u=ulim;
fu=func(u);
} else {
u=cx+GOLD*(cx-bx);
fu=func(u);
}
shft3(ax,bx,cx,u);
shft3(fa,fb,fc,fu);
}
}

inline double TOptimization::brent(double ax, double bx, double cx,
Ptrf f, double tol, double &xmin, int &flag)
{
flag = 1;
const double CGOLD=0.3819660;
const double ZEPS=1.0e-20;
int iter;
double a,b,d=0.0,etemp,fu,fv,fw,fx;
double p,q,r,tol1,tol2,u,v,w,x,xm;
double e=0.0;

a=(ax < cx ? ax : cx);
b=(ax > cx ? ax : cx);
x=w=v=bx;
fw=fv=fx=f(x);
for (iter=0;iter<ITMAX;iter++) {
xm=0.5*(a+b);
tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
if (fabs(x-xm) <= (tol2-0.5*(b-a))) {
xmin=x;
return fx;
}
if (fabs(e) > tol1) {
r=(x-w)*(fx-fv);
q=(x-v)*(fx-fw);
p=(x-v)*q-(x-w)*r;
q=2.0*(q-r);
if (q > 0.0) p = -p;
q=fabs(q);
etemp=e;
e=d;
if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
d=CGOLD*(e=(x >= xm ? a-x : b-x));
else {
d=p/q;
u=x+d;
if (u-a < tol2 || b-u < tol2)
d=SIGN(tol1,xm-x);
}
} else {
d=CGOLD*(e=(x >= xm ? a-x : b-x));
}
u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
fu=f(u);
if (fu <= fx) {
if (u >= x) a=x; else b=x;
shft3(v,w,x,u);
shft3(fv,fw,fx,fu);
} else {
if (u < x) a=u; else b=u;
if (fu <= fw || w == x) {
v=w;
w=u;
fv=fw;
fw=fu;
} else if (fu <= fv || v == x || v == w) {
v=u;
fv=fu;
}
}
}
flag = 0;
xmin=x;
return fx;
}

inline void TOptimization::linmin(double *p, double *xi, double &fret, Reff func)
{
int j, flag;
const double TOL=1.0e-8;
double xx,xmin,fx,fb,fa,bx,ax;

int n=num;
ncom=n;
//pcom_p=new Vec_Dp(n);
//xicom_p=new Vec_Dp(n);
nrfunc=func;
//Vec_Dp &pcom=*pcom_p,&xicom=*xicom_p;
double *pcom = pcom_p, *xicom = xicom_p;
for (j=0;j<n;j++) {
pcom[j]=p[j];
xicom[j]=xi[j];
}
ax=0.0;
xx=1.0;
mnbrak(ax,xx,bx,fa,fx,fb,f1dim);
fret=brent(ax,xx,bx,f1dim,TOL,xmin, flag);
for (j=0;j<n;j++) {
xi[j] *= xmin;
p[j] += xi[j];
}
//delete xicom_p;
//delete pcom_p;
}

inline bool TOptimization::powell(double *p, double **xi, double ftol, int &iter,
double &fret, Reff func)
{
const int ITMAX=500;
const double TINY=1.0e-20;
int i,j,ibig;
double del,fp,fptt,t;

int n=num;
//Vec_Dp pt(n),ptt(n),xit(n);
double *pt, *ptt, *xit;
for(i = 0; i < n; ++i)
{
pt = new double [n];
ptt = new double [n];
xit = new double [n];
}
fret=func(p);
for (j=0;j<n;j++) pt[j]=p[j];
for (iter=0;;++iter) {
fp=fret;
ibig=0;
del=0.0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) xit[j]=xi[j][i];
fptt=fret;
linmin(p,xit,fret,func);
if (fptt-fret > del) {
del=fptt-fret;
ibig=i+1;
}
}
if (2.0*(fp-fret) <= ftol*(fabs(fp)+fabs(fret))+TINY) {
delete []pt;
delete []ptt;
delete []xit;
return true;
}
if (iter == ITMAX)
{
delete []pt;
delete []ptt;
delete []xit;
return false;
//cerr<<"powell exceeding maximum iterations.";
}
for (j=0;j<n;j++) {
ptt[j]=2.0*p[j]-pt[j];
xit[j]=p[j]-pt[j];
pt[j]=p[j];
}
fptt=func(ptt);
if (fptt < fp) {
t=2.0*(fp-2.0*fret+fptt)*SQR(fp-fret-del)-del*SQR(fp-fptt);
if (t < 0.0) {
linmin(p,xit,fret,func);
for (j=0;j<n;j++) {
xi[j][ibig-1]=xi[j][n-1];
xi[j][n-1]=xit[j];
}
}
}
}
}

#endif