C#,数值计算——Dynpro的计算方法与源程序

给定向量nstate,其整数值是每个状态中的状态数阶段(第一和最后阶段为1),并给定函数成本(j,k,i)返回在阶段i的状态j和的状态k之间移动的成本阶段i+1,此例程返回与nstate长度相同的向量包含最低成本路径的状态号。状态数从0开始,并且返回向量的第一个和最后一个分量将因此总是0。

Given the vector nstate whose integer values are the number of states in each stage(1 for the first and last stages), and given a function cost(j, k, i)that returns the cost of moving between state j of stage i and state k ofstage i+1, this routine returns a vector of the same length as nstatecontaining the state numbers of the lowest cost path. States number from 0,and the first and last components of the returned vector will thus always be 0.

using System;

namespace Legalsoft.Truffer

{

/// <summary>

/// Given the vector nstate whose integer values are the number of states in each

/// stage(1 for the first and last stages), and given a function cost(j, k, i)

/// that returns the cost of moving between state j of stage i and state k of

/// stage i+1, this routine returns a vector of the same length as nstate

/// containing the state numbers of the lowest cost path. States number from 0,

/// and the first and last components of the returned vector will thus always be 0.

/// </summary>

public abstract class Dynpro

{

public Dynpro()

{

}

public abstract double cost(int jj, int kk, int ii);

public int[] dynpro(int[] nstate)

{

const double BIG = 1.0e99;

const double EPS = float.Epsilon; //numeric_limits<double>.epsilon();

int nstage = nstate.Length - 1;

int[] answer = new int[nstage + 1];

if (nstate[0] != 1 || nstate[nstage] != 1)

{

throw new Exception("One state allowed in first and last stages.");

}

double[,] best = new double[nstage + 1, nstate[0]];

best[0, 0] = 0.0;

for (int i = 1; i <= nstage; i++)

{

for (int k = 0; k < nstate[i]; k++)

{

double b = BIG;

for (int j = 0; j < nstate[i - 1]; j++)

{

double a = best[i - 1, j] + cost(j, k, i - 1);

if ((a) < b)

{

b = a;

}

}

best[i, k] = b;

}

}

answer[nstage] = answer[0] = 0;

for (int i = nstage - 1; i > 0; i--)

{

int k = answer[i + 1];

double b = best[i + 1, k];

int j = 0;

for (; j < nstate[i]; j++)

{

double temp = best[i, j] + cost(j, k, i);

if (Math.Abs(b - temp) <= EPS * Math.Abs(temp))

{

break;

}

}

answer[i] = j;

}

return answer;

}

}

}

相关推荐
易码智能5 分钟前
【EtherCATBasics】- KRTS C++示例精讲(2)
开发语言·c++·kithara·windows 实时套件·krts
一只自律的鸡6 分钟前
C语言项目 天天酷跑(上篇)
c语言·开发语言
程序猿000001号9 分钟前
使用Python的Seaborn库进行数据可视化
开发语言·python·信息可视化
鸿喵小仙女10 分钟前
C# WPF读写STM32/GD32单片机Flash数据
stm32·单片机·c#·wpf
一个不正经的林Sir14 分钟前
C#WPF基础介绍/第一个WPF程序
开发语言·c#·wpf
带多刺的玫瑰18 分钟前
Leecode刷题C语言之切蛋糕的最小总开销①
java·数据结构·算法
API快乐传递者18 分钟前
Python爬虫获取淘宝详情接口详细解析
开发语言·爬虫·python
公众号Codewar原创作者20 分钟前
R数据分析:工具变量回归的做法和解释,实例解析
开发语言·人工智能·python
赵钰老师23 分钟前
基于R语言APSIM模型应用及批量模拟(精细农业、水肥管理、气候变化、粮食安全、土壤碳周转、环境影响、农业可持续性、农业生态等)
开发语言·数据分析·r语言
巫师不要去魔法部乱说29 分钟前
PyCharm专项训练5 最短路径算法
python·算法·pycharm