我想创建一个值表,其中对于每个“t”值,函数“TabRot”计算结果,并找到“TabRot”最大的“t”值。由于我的步进间隔在以下代码中为0.001(也可以是0.00001);什么是最快的计算方法?
捕捉是可以有两个/更多相同的最大值,我只需要选择第一个。
到目前为止代码:
// Devise optimize function
for (double t = -0.025; t <= 0.025; t = t + 0.001)//theta[{t, -.05, .05, .001}]
{
//Table[t,TabRot]
DataTable TabVal = new DataTable();
TabVal.Rows.Add(RotTab.TabRot(t, i1));
}
答案 0 :(得分:1)
不清楚您的问题,但您需要实例化数据表外部循环,否则您将在每次循环迭代中创建数据表
DataTable TabVal = new DataTable();
for (double t = -0.025; t <= 0.025; t = t + 0.001)//theta[{t, -.05, .05, .001}]
{
TabVal.Rows.Add(RotTab.TabRot(t, i1));
}
根据您的评论,看起来您正在尝试存储单个标量值。在这种情况下,使用list<double>
之类的
List<double> TabVal = new List<double>();
for (double t = -0.025; t <= 0.025; t = t + 0.001)//theta[{t, -.05, .05, .001}]
{
TabVal.Add(RotTab.TabRot(t, i1));
}
填好列表后,您可以通过调用
等MAX()
方法找到最大值
TabVal.Max();
答案 1 :(得分:1)
我假设RotTab.TabRot(double,object);返回一个double。 您的评论向我表明您希望tabVal保持(t,TabRot(t,i1)),这样就可以填充它。
//Defined elsewhere: i1, RotTab[.TabRot]
//populates tabVal with (t,trot) pairs
//maxt contains the t value that produced the maximum
DataTable tabVal = new DataTable();//move this here, otherwise tabVal will only ever have the last item in it
//initialize what your columns are
tabVal.Columns.Add("t", double);
tabVal.Columns.Add("trot", double);
//These should probably be somewhere else, but for this code I'm putting them here. Magic numbers are bad, mmkay?
double start = -0.025;
double end = 0.025;
double step = 0.001;
//init to the first value, since that's definitely a valid possible max
double max = RotTab.TabRot(start, i1);
double maxt = start;
//used for holding what we're looking at.
double cur;
for (double t = start; t <= end; t += step) {
cur = RotTab.TabRot(t, i1);
if (cur > max) {
max = cur;
maxt = t;
}
tabVal.Rows.Add(new double[] {t, cur});
}
如果您要做的就是采取最大值并偶尔查找t-&gt;小跑(不想再次计算小跑),您可以使用词典代替。 可能会更有效率。
编辑:如果您需要的只是最大值,那么......
//These should probably be somewhere else, but for this code I'm putting them here. Magic numbers are bad, mmkay?
double start = -0.025;
double end = 0.025;
double step = 0.001;
double max = RotTab.TabRot(start, i1);
double maxt = start;
double cur;
for (int t = start; t <= end; t += step) {
cur = RotTab.TabRot(t, i1);
if (cur > max) {
max = cur;
maxt = t;
}
}
您不需要存储任何东西,只需找到最大值。