【问题标题】:Unity3d- calculate average of 10 most recent constantly changing floatsUnity3d - 计算 10 个最近不断变化的浮点数的平均值
【发布时间】:2021-06-09 22:09:04
【问题描述】:

我需要计算每帧调用的方法中最近 10 个浮点值的平均值,并且浮点值不断变化。

如果我有以下情况

1- 我能正确获得最近 10 个浮点数的平均值吗?

谢谢!

List<float> floatVals= new List<float> { };
Update(){

floatVals.Add(myChangingFloatVal);

if(floatVals.Count>=10){
floatVals.RemoveRange(0, 1);
_averageFloat= floatVals.Average();

}

【问题讨论】:

    标签: c# list unity3d moving-average


    【解决方案1】:

    我希望在您的平均方法之外有一个列表。另外,我看不到您的示例中您的更改浮动值在哪里发生了变化。所示的 for 循环会将相同的值推送到列表中 10 次,平均值与该值相同。考虑改成这样。

    // Max number of values to average
    //
    private int maxAverageValues = 10;
    
    // Running list of values to average
    //
    private List<float> valuesToAverage = new List<float>();
    
    private float AddValueGetAverage(float newValue)
    {
        // New values are added to the end of the list
        //
        valuesToAverage.Add(newValue);
        
        // Check if we exceeded the max amount of values we want to average
        //
        if (valuesToAverage.Count > maxAverageValues)
        {
            // Max exceeded, remove the oldest value
            //
            valuesToAverage.RemoveAt(0);
        }
    
        // Return the average
        //
        return valuesToAverage.Sum() / valuesToAverage.Count;
    }
    

    编辑

    根据 Amys 的建议,这里是使用 Queue 而不是 List 的相同代码。

    根据 Microsoft 的文档: 存储在队列中的对象在一端插入并从另一端移除。当您需要临时存储信息时,队列和堆栈很有用;也就是说,当您可能想要在检索到它的值后丢弃一个元素时。如果您需要按照存储在集合中的相同顺序访问信息,请使用队列。

    private int maxValuesForFloatingAverage = 10;
    private Queue<float> floatingAverageValues = new Queue<float>();
    
    private float changingFloat = 0f;
    private float changingFloatAvg = 0f;
    
    void Update()
    {
        // update the changing float value here...
    
        // Enqueue the new value
        //
        floatingAverageValues.Enqueue(changingFloat);
    
        // Check if we exceeded the amount of values we want to average
        //
        if (floatingAverageValues.Count > maxValuesForFloatingAverage)
        {
            // Max exceeded, dequeue the oldest item
            //
            floatingAverageValues.Dequeue();
        }
    
        // Take the average
        //
        changingFloatAvg = floatingAverageValues.Sum() / floatingAverageValues.Count;
    }
    

    【讨论】:

    • 由于您要添加到列表的末尾并从开头删除,因此可以使用 Queue&lt;float&gt; 代替。见stackoverflow.com/questions/10380692/queuet-vs-listt
    • @Amy 非常真实,很酷的建议。由于这被用作队列,我确实看到了清楚显示意图的好处。速度在这里不是什么大问题,但这也是使用队列而不是列表的另一个原因。好建议。
    • 感谢您的快速回复。我编辑了我的问题以删除 for 循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多