how to avoid the potential of an overflow when computing an average of times?

前端 未结 3 1323
故里飘歌
故里飘歌 2021-01-25 15:01

I am writing a function for getting the average of the clocks it takes to call a specific void (*)(void) aka void -> void function a specific number

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-25 15:41

    The average of the first n elements is

              SUM
    Average = ---
               n
    

    The next element Mi is

               (SUM + Mi)
    Average2 = ----------
                  n + 1
    

    So given the current average, it is possible to find the next average with the new reading.

               (Average * n + Mi )
    Average2 = -------------------
                      n + 1
    

    This can then be changed to an equation which doesn't increase

                           n      Mi
    Average2 = Average * ----- + -----
                         n + 1   n + 1
    

    In practice for timing, the size of time will fit within the datatype of the computer.

    As pointed out, this needs to use a floating point representation, and whilst will not fail due to overflow, can still fail when n/(n+1) is smaller than the accuracy of the floating point fraction part.

    Update

    From incremental average

    There is a better reorganization.

                           Mi - Average
    Average2 = Average  +  -------------
                               n + 1
    

    It is better, because it only has one division.

提交回复
热议问题