表格数据,并找到最大值c#

本文关键字:最大值 数据 表格 | 更新日期: 2023-09-27 18:02:38

我想创建一个值表,其中对于每个"t"值,函数"TabRot"计算结果,并找到"TabRot"最大的"t"值。因为我的步进间隔是0.001在下面的代码(可以是0.00001);最快的计算方法是什么?

问题是可以有两个或更多相同的最大值,我只需要选择第一个。

code so far:

// 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));
                    }

表格数据,并找到最大值c#

不清楚你的问题,但你需要在循环外实例化数据表,否则你将在每次循环迭代中创建一个数据表

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();

我假设RotTab。TabRot(双、对象);返回双精度类型。你的注释告诉我,你想要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->trot(不想再次计算trot),你可以使用Dictionary代替。可能会更有效率。

编辑:如果你需要的只是最大值,呃…

//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;
    }
}

你不需要存储任何东西,只要找到最大值就可以了。