Calculating exponential moving averages











up vote
1
down vote

favorite












I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?



time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.



lastA etc are the exponential moving averages from the last calculations.



a etc will be left with the calculated exponential moving averages.



var distance = ...;
var a = Math.pow(1.16, -(time-lastTime)),
b = Math.pow(1.19, -(time-lastTime)),
c = Math.pow(1.22, -(time-lastTime)),
d = Math.pow(1.26, -(time-lastTime)),
e = Math.pow(1.30, -(time-lastTime)),
f = Math.pow(1.35, -(time-lastTime)),
g = Math.pow(1.40, -(time-lastTime));
a = a*lastA + (1-a)*distance;
b = b*lastB + (1-b)*distance;
c = c*lastC + (1-c)*distance;
d = d*lastD + (1-d)*distance;
e = e*lastE + (1-e)*distance;
f = f*lastF + (1-f)*distance;
g = g*lastG + (1-g)*distance;









share|improve this question




























    up vote
    1
    down vote

    favorite












    I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?



    time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.



    lastA etc are the exponential moving averages from the last calculations.



    a etc will be left with the calculated exponential moving averages.



    var distance = ...;
    var a = Math.pow(1.16, -(time-lastTime)),
    b = Math.pow(1.19, -(time-lastTime)),
    c = Math.pow(1.22, -(time-lastTime)),
    d = Math.pow(1.26, -(time-lastTime)),
    e = Math.pow(1.30, -(time-lastTime)),
    f = Math.pow(1.35, -(time-lastTime)),
    g = Math.pow(1.40, -(time-lastTime));
    a = a*lastA + (1-a)*distance;
    b = b*lastB + (1-b)*distance;
    c = c*lastC + (1-c)*distance;
    d = d*lastD + (1-d)*distance;
    e = e*lastE + (1-e)*distance;
    f = f*lastF + (1-f)*distance;
    g = g*lastG + (1-g)*distance;









    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?



      time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.



      lastA etc are the exponential moving averages from the last calculations.



      a etc will be left with the calculated exponential moving averages.



      var distance = ...;
      var a = Math.pow(1.16, -(time-lastTime)),
      b = Math.pow(1.19, -(time-lastTime)),
      c = Math.pow(1.22, -(time-lastTime)),
      d = Math.pow(1.26, -(time-lastTime)),
      e = Math.pow(1.30, -(time-lastTime)),
      f = Math.pow(1.35, -(time-lastTime)),
      g = Math.pow(1.40, -(time-lastTime));
      a = a*lastA + (1-a)*distance;
      b = b*lastB + (1-b)*distance;
      c = c*lastC + (1-c)*distance;
      d = d*lastD + (1-d)*distance;
      e = e*lastE + (1-e)*distance;
      f = f*lastF + (1-f)*distance;
      g = g*lastG + (1-g)*distance;









      share|improve this question















      I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?



      time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.



      lastA etc are the exponential moving averages from the last calculations.



      a etc will be left with the calculated exponential moving averages.



      var distance = ...;
      var a = Math.pow(1.16, -(time-lastTime)),
      b = Math.pow(1.19, -(time-lastTime)),
      c = Math.pow(1.22, -(time-lastTime)),
      d = Math.pow(1.26, -(time-lastTime)),
      e = Math.pow(1.30, -(time-lastTime)),
      f = Math.pow(1.35, -(time-lastTime)),
      g = Math.pow(1.40, -(time-lastTime));
      a = a*lastA + (1-a)*distance;
      b = b*lastB + (1-b)*distance;
      c = c*lastC + (1-c)*distance;
      d = d*lastD + (1-d)*distance;
      e = e*lastE + (1-e)*distance;
      f = f*lastF + (1-f)*distance;
      g = g*lastG + (1-g)*distance;






      javascript mathematics






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '14 at 15:42

























      asked Feb 19 '14 at 15:36









      Max

      275237




      275237






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          4
          down vote













          This is border line a bad question, as not enough code is given to properly review it.



          The variables a -> g look terrible, I would create an array with the numbers you need:



          var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


          Then I would would loop over those points and create an averages object



          var averages = {},
          value, x;
          for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
          value = dataPoints[i];
          x = Math.pow(value, -(time-lastTime));
          averages[value] = x * lastAverages[value] + (1-x) * distance;
          }


          I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)






          share|improve this answer



















          • 2




            Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
            – Flambino
            Feb 20 '14 at 1:42






          • 1




            @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
            – konijn
            Feb 20 '14 at 13:24


















          up vote
          2
          down vote













          Either I'm confused by your notation, or you may have implemented something completely different from an exponential moving average, which is traditionally defined as




          $S_{t} = alpha Y_{t-1} + (1-alpha) S_{t-1}$



          where




          • $alpha$ is the decay rate

          • $Y_{t}$ is the value at time $t$

          • $S_{t}$ is the exponential moving average at time $t$.




          How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:




          var distance = ...;
          var a = Math.pow(1.16, -(time-lastTime));
          a = a*lastA + (1-a)*distance;



          I'm guessing





          • a corresponds to $alpha$, and you adjust the decay per timeslice based on the duration of the timeslice


          • lastA corresponds to $Y_{t-1}$


          • distance corresponds to $S_{t-1}$


          But then, I'm confused:




          1. What's the purpose of the seven letters ag? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series St for each decay rate?

          2. Why do all seven cases all share the same distance — isn't it the point to have a different distance series for each case?

          3. Why do you assign the final result to a (= the decay rate) rather than to distance or something?






          share|improve this answer























            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f42157%2fcalculating-exponential-moving-averages%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            4
            down vote













            This is border line a bad question, as not enough code is given to properly review it.



            The variables a -> g look terrible, I would create an array with the numbers you need:



            var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


            Then I would would loop over those points and create an averages object



            var averages = {},
            value, x;
            for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
            value = dataPoints[i];
            x = Math.pow(value, -(time-lastTime));
            averages[value] = x * lastAverages[value] + (1-x) * distance;
            }


            I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)






            share|improve this answer



















            • 2




              Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
              – Flambino
              Feb 20 '14 at 1:42






            • 1




              @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
              – konijn
              Feb 20 '14 at 13:24















            up vote
            4
            down vote













            This is border line a bad question, as not enough code is given to properly review it.



            The variables a -> g look terrible, I would create an array with the numbers you need:



            var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


            Then I would would loop over those points and create an averages object



            var averages = {},
            value, x;
            for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
            value = dataPoints[i];
            x = Math.pow(value, -(time-lastTime));
            averages[value] = x * lastAverages[value] + (1-x) * distance;
            }


            I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)






            share|improve this answer



















            • 2




              Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
              – Flambino
              Feb 20 '14 at 1:42






            • 1




              @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
              – konijn
              Feb 20 '14 at 13:24













            up vote
            4
            down vote










            up vote
            4
            down vote









            This is border line a bad question, as not enough code is given to properly review it.



            The variables a -> g look terrible, I would create an array with the numbers you need:



            var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


            Then I would would loop over those points and create an averages object



            var averages = {},
            value, x;
            for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
            value = dataPoints[i];
            x = Math.pow(value, -(time-lastTime));
            averages[value] = x * lastAverages[value] + (1-x) * distance;
            }


            I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)






            share|improve this answer














            This is border line a bad question, as not enough code is given to properly review it.



            The variables a -> g look terrible, I would create an array with the numbers you need:



            var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


            Then I would would loop over those points and create an averages object



            var averages = {},
            value, x;
            for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
            value = dataPoints[i];
            x = Math.pow(value, -(time-lastTime));
            averages[value] = x * lastAverages[value] + (1-x) * distance;
            }


            I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 20 '14 at 15:45









            200_success

            127k15148412




            127k15148412










            answered Feb 19 '14 at 20:44









            konijn

            26.9k453235




            26.9k453235








            • 2




              Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
              – Flambino
              Feb 20 '14 at 1:42






            • 1




              @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
              – konijn
              Feb 20 '14 at 13:24














            • 2




              Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
              – Flambino
              Feb 20 '14 at 1:42






            • 1




              @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
              – konijn
              Feb 20 '14 at 13:24








            2




            2




            Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
            – Flambino
            Feb 20 '14 at 1:42




            Why use objects for storage, though? Just use plain arrays for averages and lastAverages. Indices will match the dataPoints array. Using numbers as property names is iffy, as they'll get treated as strings and whatnot.
            – Flambino
            Feb 20 '14 at 1:42




            1




            1




            @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
            – konijn
            Feb 20 '14 at 13:24




            @200_success I think the code conveys my point. The original code cannot run, so I cannot test and fix mistakes.
            – konijn
            Feb 20 '14 at 13:24












            up vote
            2
            down vote













            Either I'm confused by your notation, or you may have implemented something completely different from an exponential moving average, which is traditionally defined as




            $S_{t} = alpha Y_{t-1} + (1-alpha) S_{t-1}$



            where




            • $alpha$ is the decay rate

            • $Y_{t}$ is the value at time $t$

            • $S_{t}$ is the exponential moving average at time $t$.




            How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:




            var distance = ...;
            var a = Math.pow(1.16, -(time-lastTime));
            a = a*lastA + (1-a)*distance;



            I'm guessing





            • a corresponds to $alpha$, and you adjust the decay per timeslice based on the duration of the timeslice


            • lastA corresponds to $Y_{t-1}$


            • distance corresponds to $S_{t-1}$


            But then, I'm confused:




            1. What's the purpose of the seven letters ag? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series St for each decay rate?

            2. Why do all seven cases all share the same distance — isn't it the point to have a different distance series for each case?

            3. Why do you assign the final result to a (= the decay rate) rather than to distance or something?






            share|improve this answer



























              up vote
              2
              down vote













              Either I'm confused by your notation, or you may have implemented something completely different from an exponential moving average, which is traditionally defined as




              $S_{t} = alpha Y_{t-1} + (1-alpha) S_{t-1}$



              where




              • $alpha$ is the decay rate

              • $Y_{t}$ is the value at time $t$

              • $S_{t}$ is the exponential moving average at time $t$.




              How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:




              var distance = ...;
              var a = Math.pow(1.16, -(time-lastTime));
              a = a*lastA + (1-a)*distance;



              I'm guessing





              • a corresponds to $alpha$, and you adjust the decay per timeslice based on the duration of the timeslice


              • lastA corresponds to $Y_{t-1}$


              • distance corresponds to $S_{t-1}$


              But then, I'm confused:




              1. What's the purpose of the seven letters ag? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series St for each decay rate?

              2. Why do all seven cases all share the same distance — isn't it the point to have a different distance series for each case?

              3. Why do you assign the final result to a (= the decay rate) rather than to distance or something?






              share|improve this answer

























                up vote
                2
                down vote










                up vote
                2
                down vote









                Either I'm confused by your notation, or you may have implemented something completely different from an exponential moving average, which is traditionally defined as




                $S_{t} = alpha Y_{t-1} + (1-alpha) S_{t-1}$



                where




                • $alpha$ is the decay rate

                • $Y_{t}$ is the value at time $t$

                • $S_{t}$ is the exponential moving average at time $t$.




                How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:




                var distance = ...;
                var a = Math.pow(1.16, -(time-lastTime));
                a = a*lastA + (1-a)*distance;



                I'm guessing





                • a corresponds to $alpha$, and you adjust the decay per timeslice based on the duration of the timeslice


                • lastA corresponds to $Y_{t-1}$


                • distance corresponds to $S_{t-1}$


                But then, I'm confused:




                1. What's the purpose of the seven letters ag? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series St for each decay rate?

                2. Why do all seven cases all share the same distance — isn't it the point to have a different distance series for each case?

                3. Why do you assign the final result to a (= the decay rate) rather than to distance or something?






                share|improve this answer














                Either I'm confused by your notation, or you may have implemented something completely different from an exponential moving average, which is traditionally defined as




                $S_{t} = alpha Y_{t-1} + (1-alpha) S_{t-1}$



                where




                • $alpha$ is the decay rate

                • $Y_{t}$ is the value at time $t$

                • $S_{t}$ is the exponential moving average at time $t$.




                How do your variables correspond to those in the definition? Let's just consider one of your letters instead of all seven:




                var distance = ...;
                var a = Math.pow(1.16, -(time-lastTime));
                a = a*lastA + (1-a)*distance;



                I'm guessing





                • a corresponds to $alpha$, and you adjust the decay per timeslice based on the duration of the timeslice


                • lastA corresponds to $Y_{t-1}$


                • distance corresponds to $S_{t-1}$


                But then, I'm confused:




                1. What's the purpose of the seven letters ag? To track the results using multiple decay rates? If so, wouldn't the different decay rates result in a different series St for each decay rate?

                2. Why do all seven cases all share the same distance — isn't it the point to have a different distance series for each case?

                3. Why do you assign the final result to a (= the decay rate) rather than to distance or something?







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 2 '15 at 18:34









                Makoto

                203210




                203210










                answered Feb 20 '14 at 7:12









                200_success

                127k15148412




                127k15148412






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f42157%2fcalculating-exponential-moving-averages%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Morgemoulin

                    Scott Moir

                    Souastre