Adjustment of window length with sliding/moving RMS method for frequency drifts I'm using a sliding RMS mechanism to compute RMS of a signal, i.e. with a window size of N, I add the squared value of the new sample $x[n]$ to the running total while deducting the squared value of the $x[n - N]$ sample and then performing a square root to get the RMS value.

This method works fine when a cycle's worth data in the signal under question lines up exactly with the length of the window. For ex,

Let the window length $N = 512$, frequency of the signal $f=100 \ \mathrm{Hz}$ and sampling frequency $f_s= 51200  \ \mathrm{Hz}$.

With the above settings, every set of 512 samples would have a cycle's worth data of the signal and the computation works fine.


Now, the issue begins when the frequency of the signal deviates from $100  \ \mathrm{Hz}$ giving more or less number of samples in the same 512 samples window which throws off the accuracy of the sliding RMS algorithm.


This happens because the division by 512 to get the RMS, is no longer valid due to the fact that this particular cycle of the signal is getting complete before the end of the 512 samples window. However, the running squared total would already have the contributions from the previous samples which were divided by 512 while the samples of this cycle would require a different window length.

Is there a way to compensate for the addition/lack of samples due to the frequency drifts while using this technique?
You're right that when you're using this method to calculate the RMS value of a sinusoid, it's sensitive to getting an integer number of periods of that sinusoid in the observation window. I can see a couple ways to tweak your approach:


Since it's important to get full periods into your estimate, you could add some tracking of the sinusoid's frequency and phase. In the most complicated implementation, this could be a full-blown phase-locked loop. I've seen embedded RMS measurement systems before where this approach is used. Basically, you create  a PLL that is locked to your input signal, then use the locked phase and frequency to ensure you take samples across as close to an integer number of periods as you can.

A somewhat simpler way of doing this is as follows: consider processing datasets like those you plotted above. If the data should have approximately one period of the signal, then you can get a finer estimate of the period by locating the sinusoid's zero crossings. Once you've estimated the period, then you can use that subset of the data for your RMS calculation. This might be sufficient, depending upon the accuracy that your application requires.
Thinking a bit outside the box: is the input signal a very pure sinusoid (with negligible noise), and is it always significantly oversampled? You could dispense with the RMS approach altogether and simply look for peak amplitude, then use this to calculate the sinusoid's RMS level.