【问题标题】:Calculate the ticks of an axis for a chart with a stepsize计算具有步长的图表的轴刻度
【发布时间】:2019-03-29 09:39:30
【问题描述】:

我已经计算了图表上轴的步长。

我还有最小值和最大值。现在我需要计算所有刻度,以便显示 Min 和 Max 之间的所有值。

例如:

步长:1000

最低:213

最大:4405

预期报价:0,1000,2000,3000,4000,5000


步长:500

最小值:-1213

最大:1405

预期报价:-1500,-1000,-500,0,500,1000,1500

到目前为止,我正在尝试使用“尝试和错误”来计算第一个值,例如:

bool firstStepSet = false;
double firstStep = stepSize;
do
{
    if (xValue >= (firstStep - (stepSize / 2)) && xValue <= 
    (firstStep + (stepSize / 2)))
    {
        firstStepSet = true;
        this.myBarXValues.Add(firstStep, 0);
    }
    else if (xValue > stepSize)
    {
        firstStep += stepSize;
    }
    else
    {
        firstStep -= stepSize;
    }
}
while (!firstStepSet);

然后,我将向此列表添加步骤,直到所有值都适合。

这对我来说似乎很脏,我想知道是否有其他解决方案。

所以我需要一个计算我需要的第一个刻度的解决方案。

【问题讨论】:

  • 你说的是 MSChart 还是你从头写的东西?

标签: c# .net algorithm math


【解决方案1】:

这个函数计算第一步和最后一步的值:

static void CalcSteps(int min, int max, int stepSize, out int firstStep, out int lastStep)
{
    if (min >= 0)
    {
        firstStep = (min / stepSize) * stepSize;
    }
    else
    {
        firstStep = ((min - stepSize + 1) / stepSize) * stepSize;
    }

    if (max >= 0)
    {
        lastStep = ((max + stepSize - 1) / stepSize) * stepSize;
    }
    else
    {
        lastStep = (max / stepSize) * stepSize;
    }
}

【讨论】:

    【解决方案2】:

    您可以使用整数四舍五入来计算轴限制,以降低和更高的值

    low = stepsize * (min / stepsize)  //integer division needed
    high = stepsize * ((max + stepsize - 1) / stepsize)
    

    示例 Python 代码返回限制和刻度数(比间隔计数多一个)

    def getminmax(minn, maxx, step):
        low = (minn // step)
        high = (maxx + step - 1) // step
        ticks = high - low + 1
        return low * step, high * step, ticks
    
    
    print(getminmax(213, 4405, 1000))
    print(getminmax(-1213,1405, 500))
    
    (0, 5000, 6)
    (-1500, 1500, 7)
    

    【讨论】:

    • 在我的情况下不适用于负数。示例: (int)(-2600/5000) 结果为 0
    • @Daniel Rose 因为 CSharp 中的 int 用作舍入为零,而不是 -infinity(不同的语言使用不同的规则)
    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多