如何在 C# 中计算变量随时间的变化率?

How to calculate the rate of change of a variable over time in C#?

我需要实现一种适应变量变化率的算法。假设我有一个整数 HumidityPercent 和一个实时提供数据的外部传感器。 我找到了几种方法来检测我的 var 是否已更改:

private float HumChange 
    {
        get { return HumidityPercent; }
        set 
        {
            HumidityPercent = value;
            if (HumidityPercent != 100)
            {
                // Do what?
            }           
        }
    }

我有一个计时器(秒表)来计算经过的毫秒数。问题是:如何调用新变量的更改来存储毫秒和新值?

 private double newHum = (HumidityPercent, timer.TotalMilliseconds);

但是之后怎么区分呢?

如有任何帮助,我们将不胜感激。

如果你需要变化率,那么你需要具备三个条件:

  1. 原值。
  2. 新值。
  3. 这些值之间的时间差。

如果你有一个定时器 运行 那么它第一次启动时它需要做的就是存储湿度。

下次触发时需要将 "current" 值移动到 "previous" 值,更新 "current" 值并计算变化率。

因此,如果您的值是可为 null 的双精度值,您可以测试是否有以前的值:

private double? previous;
private double current;
private double rateOfChange;

private void TimerTick(....)
{
    if (previous == null)
    {
        current = GetHumidity();
    }
    else
    {
        previous = current;
        current = GetHumidity();
        rateOfChange = (current - previous) / time;
    }
}

经过彻底搜索(以及我这边的大量学习)后,我在@ChrisF 代码的基础上进行了构建,并制作了一个高效而优雅的简洁代码片段。

    public void InitTimer()
    {
        timer = new System.Timers.Timer();
        timer.Enabled = true;
        timer.Elapsed += timer_Tick;
        timer.Interval = 200;
    }

    public void timer_Tick(object sender, System.Timers.ElapsedEventArgs e) 
    {
        timer.Enabled = false;
        System.Threading.Interlocked.Increment(ref current);
        if (current == 0)
        {
            current = HumidityPercent;
        }
        else
        {
            previous = current;
            current = HumidityPercent;
            RateOfChange = (current-previous)/5;
            Thread.Sleep(200);
        }
        timer.Enabled = true;
    }

注意到我必须调用一次 InitTimer 方法,所以我使用了:

    if (firstrun == true)
    {
        InitTimer();
        firstrun = false;
    }   

另请注意,我已将滴答声夹在停止-启动事件中,放入 Thread.Sleep 并添加了非常方便且高效的 System.Threading.Interlocked.Increment(ref current)。

感谢大家的贡献!