Root mean square of a function in python

Question:

I want to calculate root mean square of a function in Python. My function is in a simple form like y = f(x). x and y are arrays.

I tried Numpy and Scipy Docs and couldn’t find anything.

Asked By: user4179448

||

Answers:

I’m going to assume that you want to compute the expression given by the following pseudocode:

ms = 0
for i = 1 ... N
    ms = ms + y[i]^2
ms = ms / N
rms = sqrt(ms)

i.e. the square root of the mean of the squared values of elements of y.

In numpy, you can simply square y, take its mean and then its square root as follows:

rms = np.sqrt(np.mean(y**2))

So, for example:

>>> y = np.array([0, 0, 1, 1, 0, 1, 0, 1, 1, 1])  # Six 1's
>>> y.size
10
>>> np.mean(y**2)
0.59999999999999998
>>> np.sqrt(np.mean(y**2))
0.7745966692414834

Do clarify your question if you mean to ask something else.

Answered By: Praveen

You could use the sklearn function

from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_actual,[0 for _ in y_actual], squared=False)
Answered By: Peter Cotton

numpy.std(x) tends to rms(x) in cases of mean(x) value tends to 0 (thanks to @Seb), like it can be with sound records, vibrations, and other signals of fluctuations from zero.

rms = lambda x_seq: (sum(x*x for x in x_seq)/len(x_seq))**(1/2)

Answered By: Александр

In case you’d like to frame your array before compute RMS, this is a numpy solution:

nframes = 1000
rms = np.array([
    np.sqrt(np.mean(arr**2)) 
    for arr in np.array_split(arr,nframes)
])

If you’d like to specify frame length instead of frame counts, you’d do this first:

frame_length = 200
arr_length = arr.shape[0]
nframes = arr_length // frame_length +1
Answered By: C.K.

Simply use math.dist(x, y). RMS is basically Euclidian distance in N dimensions.

Answered By: Khanh N