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

📄 conjugate.cpp

📁 实现共轭梯度法的实例
💻 CPP
字号:
// Conjugate.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "Frprmn.h"
#include "Dfpmin.h"
#include "functions.h"

const int n=2;

double a1=1.0,b1=1.0,c1=1.0;
double a2=2.0,b2=0.5,c2=0.5;


//目标值函数
double fun(double p[])
{
	return pow(a1*sin(p[1])+b1*cos(p[2]-0.5)*cos(p[1])-c1,2.0)+\
		pow(a2*sin(p[1])+b2*cos(p[2]-1)*cos(p[1])-c2,2.0);
}

//梯度值函数
void dfun(double p[],double x[])
{
	x[1]=2*(a1*sin(p[1])+b1*cos(p[2]-0.5)*cos(p[1])-c1)*\
		(a1*cos(p[1])-b1*cos(p[2]-0.5)*sin(p[1]))+\
		2*(a2*sin(p[1])+b2*cos(p[2]-1)*cos(p[1])-c2)*\
		(a2*cos(p[1])-b2*cos(p[2]-1)*sin(p[1]));
	x[2]=-2*(a1*sin(p[1])+b1*cos(p[2]-0.5)*cos(p[1])-c1)*\
		b1*cos(p[2]-0.5)*cos(p[1])-\
		2*(a2*sin(p[1])+b2*cos(p[2]-1)*cos(p[1])-c2)*\
		b2*cos(p[2]-1)*cos(p[1]);
}

void main()
{
	double p[n+1];//迭代变量
	double ftol=1e-16;//计算精度
	double fret;//目标值
	int iter;//迭代次数
	int i;
	p[1]=0;
	p[2]=0;//赋初值
	frprmn(p,n,ftol,&iter,&fret,fun,dfun);
	printf("迭代结果\n");
	for(i=1;i<n+1;i++)
		printf("%16.14f\t",p[i]);
	printf("\n");
	printf("极小值:\t%16.14f\n",fret);
	printf("迭代次数:\t%d\n",iter);

	p[1]=0;
	p[2]=0;//赋初值
	dfpmin(p,n,ftol,&iter,&fret,fun,dfun);
	printf("迭代结果\n");
	for(i=1;i<n+1;i++)
		printf("%16.14f\t",p[i]);
	printf("\n");
	printf("极小值:\t%16.14f\n",fret);
	printf("迭代次数:\t%d\n",iter);
}

⌨️ 快捷键说明

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