Averages/Root mean square: Difference between revisions

From Rosetta Code
Content added Content deleted
m (syntax highlighting fixup automation)
imported>Arakov
 
(16 intermediate revisions by 12 users not shown)
Line 1: Line 1:
{{task}}
{{task}}


;Task
{{task heading}}


Compute the   [[wp:Root mean square|Root mean square]]   of the numbers 1..10.
Compute the   [[wp:Root mean square|Root mean square]]   of the numbers 1..10.
Line 14: Line 14:




{{task heading|See also}}
;See also


{{Related tasks/Statistical measures}}
{{Related tasks/Statistical measures}}
Line 22: Line 22:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=11l>F qmean(num)
<syntaxhighlight lang="11l">F qmean(num)
R sqrt(sum(num.map(n -> n * n)) / Float(num.len))
R sqrt(sum(num.map(n -> n * n)) / Float(num.len))


Line 33: Line 33:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang=Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


BYTE FUNC Equal(REAL POINTER a,b)
BYTE FUNC Equal(REAL POINTER a,b)
Line 84: Line 84:


=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=Ada>with Ada.Float_Text_IO; use Ada.Float_Text_IO;
<syntaxhighlight lang="ada">with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
Line 113: Line 113:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<syntaxhighlight lang=algol68># Define the rms PROCedure & ABS OPerators for LONG... REAL #
<syntaxhighlight lang="algol68"># Define the rms PROCedure & ABS OPerators for LONG... REAL #
MODE RMSFIELD = #LONG...# REAL;
MODE RMSFIELD = #LONG...# REAL;
PROC (RMSFIELD)RMSFIELD rms field sqrt = #long...# sqrt;
PROC (RMSFIELD)RMSFIELD rms field sqrt = #long...# sqrt;
Line 148: Line 148:
=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
Because ALGOL-M lacks a built-in square root function, we have to supply our own.
Because ALGOL-M lacks a built-in square root function, we have to supply our own.
<syntaxhighlight lang=algol>
<syntaxhighlight lang="algol">
BEGIN
BEGIN


Line 192: Line 192:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<syntaxhighlight lang=algolw>begin
<syntaxhighlight lang="algolw">begin
% computes the root-mean-square of an array of numbers with %
% computes the root-mean-square of an array of numbers with %
% the specified lower bound (lb) and upper bound (ub) %
% the specified lower bound (lb) and upper bound (ub) %
Line 219: Line 219:


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang=APL> rms←{((+/⍵*2)÷⍴⍵)*0.5}
<syntaxhighlight lang="apl"> rms←{((+/⍵*2)÷⍴⍵)*0.5}
x←⍳10
x←⍳10


Line 226: Line 226:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}( ES6 version )
{{Trans|JavaScript}}( ES6 version )
<syntaxhighlight lang=AppleScript>-- rootMeanSquare :: [Num] -> Real
<syntaxhighlight lang="applescript">--------------------- ROOT MEAN SQUARE -------------------

-- rootMeanSquare :: [Num] -> Real
on rootMeanSquare(xs)
on rootMeanSquare(xs)
script
script
Line 239: Line 242:




-- TEST -----------------------------------------------------------------------
--------------------------- TEST -------------------------
on run
on run
Line 248: Line 251:




-- GENERIC FUNCTIONS ----------------------------------------------------------
-------------------- GENERIC FUNCTIONS -------------------


-- foldl :: (a -> b -> a) -> a -> [b] -> a
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 275: Line 278:
{{Out}}
{{Out}}
<pre>6.204836822995</pre>
<pre>6.204836822995</pre>
----

===Straightforward===
<syntaxhighlight lang="applescript">on rootMeanSquare(listOfNumbers)
script o
property lst : listOfNumbers
end script
set r to 0.0
repeat with n in o's lst
set r to r + (n ^ 2)
end repeat
return (r / (count o's lst)) ^ 0.5
end rootMeanSquare

rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})</syntaxhighlight>

{{output}}
<syntaxhighlight lang="applescript">6.204836822995</syntaxhighlight>
===Integer range alternative===
{{Trans|AutoHotKey}} '''("Avoiding a loop" solution)'''
<syntaxhighlight lang="applescript">
-- RMS of integer range a to b.
on rootMeanSquare(a, b)
return ((b * (b + 1) * (2 * b + 1) - a * (a - 1) * (2 * a - 1)) / 6 / (b - a + 1)) ^ 0.5
end rootMeanSquare

rootMeanSquare(1, 10)</syntaxhighlight>

{{output}}
<syntaxhighlight lang="applescript">6.204836822995</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>rootMeanSquare: function [arr]->
<syntaxhighlight lang="rebol">rootMeanSquare: function [arr]->
sqrt (sum map arr 'i -> i^2) // size arr
sqrt (sum map arr 'i -> i^2) // size arr


Line 288: Line 322:


=={{header|Astro}}==
=={{header|Astro}}==
<syntaxhighlight lang=python>sqrt(mean(x²))</syntaxhighlight>
<syntaxhighlight lang="python">sqrt(mean(x²))</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
===Using a loop===
===Using a loop===
<syntaxhighlight lang=autohotkey>MsgBox, % RMS(1, 10)
<syntaxhighlight lang="autohotkey">MsgBox, % RMS(1, 10)




Line 313: Line 347:
We can show that:<br>
We can show that:<br>
<math>\sum_{i=a}^b i^2 = \frac{b(b+1)(2b+1)-a(a-1)(2a-1)}{6}</math>
<math>\sum_{i=a}^b i^2 = \frac{b(b+1)(2b+1)-a(a-1)(2a-1)}{6}</math>
<syntaxhighlight lang=autohotkey>MsgBox, % RMS(1, 10)
<syntaxhighlight lang="autohotkey">MsgBox, % RMS(1, 10)




Line 327: Line 361:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
# computes RMS of the 1st column of a data file
# computes RMS of the 1st column of a data file
{
{
Line 344: Line 378:
Note that this will work in [[Visual Basic]] and the Windows versions of [[PowerBASIC]] by simply wrapping the module-level code into the <code>MAIN</code> function, and changing <code>PRINT</code> to <code>MSGBOX</code>.
Note that this will work in [[Visual Basic]] and the Windows versions of [[PowerBASIC]] by simply wrapping the module-level code into the <code>MAIN</code> function, and changing <code>PRINT</code> to <code>MSGBOX</code>.


<syntaxhighlight lang=qbasic>DIM i(1 TO 10) AS DOUBLE, L0 AS LONG
<syntaxhighlight lang="qbasic">DIM i(1 TO 10) AS DOUBLE, L0 AS LONG
FOR L0 = 1 TO 10
FOR L0 = 1 TO 10
i(L0) = L0
i(L0) = L0
Line 363: Line 397:
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===


<syntaxhighlight lang=ApplesoftBasic> 10 N = 10
<syntaxhighlight lang="applesoftbasic"> 10 N = 10
20 FOR I = 1 TO N
20 FOR I = 1 TO N
30 S = S + I * I
30 S = S + I * I
Line 372: Line 406:
{{out}}
{{out}}
<pre>6.20483683</pre>
<pre>6.20483683</pre>

==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">precision 8

let n = 10

for i = 1 to n

let s = s + i * i

next i

print sqrt(s / n)</syntaxhighlight>
{{out| Output}}<pre>6.20483682</pre>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS-BASIC>100 PRINT RMS(10)
<syntaxhighlight lang="is-basic">100 PRINT RMS(10)
110 DEF RMS(N)
110 DEF RMS(N)
120 LET R=0
120 LET R=0
Line 384: Line 432:


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
<syntaxhighlight lang=basic>10 FAST
<syntaxhighlight lang="basic">10 FAST
20 LET RMS=0
20 LET RMS=0
30 FOR X=1 TO 10
30 FOR X=1 TO 10
Line 396: Line 444:


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<syntaxhighlight lang=bbcbasic> DIM array(9)
<syntaxhighlight lang="bbcbasic"> DIM array(9)
array() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
array() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Line 406: Line 454:
=={{header|BQN}}==
=={{header|BQN}}==
RMS is a tacit function which computes root mean square.
RMS is a tacit function which computes root mean square.
<syntaxhighlight lang=bqn>RMS ← √+´∘ט÷≠
<syntaxhighlight lang="bqn">RMS ← √+´∘ט÷≠


RMS 1+↕10</syntaxhighlight>
RMS 1+↕10</syntaxhighlight>
<lang>6.2048368229954285</syntaxhighlight>
<syntaxhighlight lang="text">6.2048368229954285</syntaxhighlight>


[https://mlochbaum.github.io/BQN/try.html#code=Uk1TIOKGkCDiiJorwrTiiJjDl8ucw7fiiaAKClJNUyAxK+KGlTEw Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=Uk1TIOKGkCDiiJorwrTiiJjDl8ucw7fiiaAKClJNUyAxK+KGlTEw Try It!]


Another solution is to take the arithmetic mean <code>+´÷≠</code> under the square (<code>ט</code>) function. Under (<code>⌾</code>) squares the arguments, then applies the mean, then inverts the square function.
Another solution is to take the arithmetic mean <code>+´÷≠</code> under the square (<code>ט</code>) function. Under (<code>⌾</code>) squares the arguments, then applies the mean, then inverts the square function.
<syntaxhighlight lang=bqn>RMS ← (+´÷≠)⌾(ט)</syntaxhighlight>
<syntaxhighlight lang="bqn">RMS ← (+´÷≠)⌾(ט)</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
#include <math.h>


Line 437: Line 485:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace rms
namespace rms
Line 462: Line 510:
An alternative method demonstrating the more functional style introduced by LINQ and lambda expressions in C# 3.
An alternative method demonstrating the more functional style introduced by LINQ and lambda expressions in C# 3.
{{works with|C sharp|C#|3}}
{{works with|C sharp|C#|3}}
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 483: Line 531:


=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang=Cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <vector>
#include <cmath>
#include <cmath>
Line 502: Line 550:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=clojure>
<syntaxhighlight lang="clojure">
(defn rms [xs]
(defn rms [xs]
(Math/sqrt (/ (reduce + (map #(* % %) xs))
(Math/sqrt (/ (reduce + (map #(* % %) xs))
Line 515: Line 563:
=={{header|COBOL}}==
=={{header|COBOL}}==
Could be written more succinctly, with an inline loop and more <tt>COMPUTE</tt> statements; but that wouldn't be very COBOLic.
Could be written more succinctly, with an inline loop and more <tt>COMPUTE</tt> statements; but that wouldn't be very COBOLic.
<syntaxhighlight lang=cobol>IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. QUADRATIC-MEAN-PROGRAM.
PROGRAM-ID. QUADRATIC-MEAN-PROGRAM.
DATA DIVISION.
DATA DIVISION.
Line 541: Line 589:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<syntaxhighlight lang=coffeescript> root_mean_square = (ary) ->
<syntaxhighlight lang="coffeescript"> root_mean_square = (ary) ->
sum_of_squares = ary.reduce ((s,x) -> s + x*x), 0
sum_of_squares = ary.reduce ((s,x) -> s + x*x), 0
return Math.sqrt(sum_of_squares / ary.length)
return Math.sqrt(sum_of_squares / ary.length)
Line 548: Line 596:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<syntaxhighlight lang=lisp>(loop for x from 1 to 10
<syntaxhighlight lang="lisp">(loop for x from 1 to 10
for xx = (* x x)
for xx = (* x x)
for n from 1
for n from 1
Line 556: Line 604:
Here's a non-iterative solution.
Here's a non-iterative solution.


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(defun root-mean-square (numbers)
(defun root-mean-square (numbers)
"Takes a list of numbers, returns their quadratic mean."
"Takes a list of numbers, returns their quadratic mean."
Line 568: Line 616:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<syntaxhighlight lang=ruby>def rms(seq)
<syntaxhighlight lang="ruby">def rms(seq)
Math.sqrt(seq.sum { |x| x*x } / seq.size)
Math.sqrt(seq.sum { |x| x*x } / seq.size)
end
end
Line 578: Line 626:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio, std.math, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.range;


real rms(R)(R d) pure {
real rms(R)(R d) pure {
Line 593: Line 641:


=={{header|Delphi}}/{{header|Pascal}}==
=={{header|Delphi}}/{{header|Pascal}}==
<syntaxhighlight lang=Delphi>program AveragesMeanSquare;
<syntaxhighlight lang="delphi">program AveragesMeanSquare;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 618: Line 666:
=={{header|E}}==
=={{header|E}}==
Using the same generic mean function as used in [[../Pythagorean means#E|pythagorean means]]:
Using the same generic mean function as used in [[../Pythagorean means#E|pythagorean means]]:
<syntaxhighlight lang=e>def makeMean(base, include, finish) {
<syntaxhighlight lang="e">def makeMean(base, include, finish) {
return def mean(numbers) {
return def mean(numbers) {
var count := 0
var count := 0
Line 632: Line 680:
def RMS := makeMean(0, fn b,x { b+x**2 }, fn acc,n { (acc/n).sqrt() })</syntaxhighlight>
def RMS := makeMean(0, fn b,x { b+x**2 }, fn acc,n { (acc/n).sqrt() })</syntaxhighlight>


<syntaxhighlight lang=e>? RMS(1..10)
<syntaxhighlight lang="e">? RMS(1..10)
# value: 6.2048368229954285</syntaxhighlight>
# value: 6.2048368229954285</syntaxhighlight>

=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight lang=easylang>
func rms v[] .
for v in v[]
sum += v * v
.
return sqrt (sum / len v[])
.
v[] = [ 1 2 3 4 5 6 7 8 9 10 ]
print rms v[]
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(define (rms xs)
(define (rms xs)
(sqrt (// (for/sum ((x xs)) (* x x)) (length xs))))
(sqrt (// (for/sum ((x xs)) (* x x)) (length xs))))
Line 646: Line 707:
=={{header|Elena}}==
=={{header|Elena}}==
{{trans|C#}}
{{trans|C#}}
ELENA 5.0 :
ELENA 6.x :
<syntaxhighlight lang=elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import system'math;
import system'math;
Line 654: Line 715:
{
{
get RootMeanSquare()
get RootMeanSquare()
= (self.selectBy:(x => x * x).summarize(Real.new()) / self.Length).sqrt();
= (self.selectBy::(x => x * x).summarize(Real.new()) / self.Length).sqrt();
}
}
Line 667: Line 728:


=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang=elixir>
<syntaxhighlight lang="elixir">
defmodule RC do
defmodule RC do
def root_mean_square(enum) do
def root_mean_square(enum) do
Line 689: Line 750:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<Lang lisp>(defun rms (nums)
<syntaxhighlight lang="lisp">(defun rms (nums)
(sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums))
(sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums))
(float (length nums)))))
(float (length nums)))))
Line 699: Line 760:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>rms(Nums) ->
<syntaxhighlight lang="erlang">rms(Nums) ->
math:sqrt(lists:foldl(fun(E,S) -> S+E*E end, 0, Nums) / length(Nums)).
math:sqrt(lists:foldl(fun(E,S) -> S+E*E end, 0, Nums) / length(Nums)).


Line 707: Line 768:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
PROGRAM ROOT_MEAN_SQUARE
PROGRAM ROOT_MEAN_SQUARE
BEGIN
BEGIN
Line 721: Line 782:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>function rms(sequence s)
<syntaxhighlight lang="euphoria">function rms(sequence s)
atom sum
atom sum
if length(s) = 0 then
if length(s) = 0 then
Line 741: Line 802:
===Cell reference expression===
===Cell reference expression===
If values are entered in the cells A1 to A10, the below expression will give the RMS value
If values are entered in the cells A1 to A10, the below expression will give the RMS value
<syntaxhighlight lang=excel>
<syntaxhighlight lang="excel">
=SQRT(SUMSQ($A1:$A10)/COUNT($A1:$A10))
=SQRT(SUMSQ($A1:$A10)/COUNT($A1:$A10))
</syntaxhighlight>
</syntaxhighlight>
Line 755: Line 816:
{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}


<syntaxhighlight lang=lisp>ROOTMEANSQR
<syntaxhighlight lang="lisp">ROOTMEANSQR
=LAMBDA(xs,
=LAMBDA(xs,
SQRT(SUMSQ(xs)/COUNT(xs))
SQRT(SUMSQ(xs)/COUNT(xs))
Line 762: Line 823:
For this test, we assume that the following generic lambda is also bound to the name ENUMFROMTO in the Name Manager:
For this test, we assume that the following generic lambda is also bound to the name ENUMFROMTO in the Name Manager:


<syntaxhighlight lang=lisp>ENUMFROMTO
<syntaxhighlight lang="lisp">ENUMFROMTO
=LAMBDA(a,
=LAMBDA(a,
LAMBDA(z,
LAMBDA(z,
Line 790: Line 851:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Uses a lambda expression and function piping.
Uses a lambda expression and function piping.
<syntaxhighlight lang=Fsharp>let RMS (x:float list) : float = List.map (fun y -> y**2.0) x |> List.average |> System.Math.Sqrt
<syntaxhighlight lang="fsharp">let RMS (x:float list) : float = List.map (fun y -> y**2.0) x |> List.average |> System.Math.Sqrt


let res = RMS [1.0..10.0]</syntaxhighlight>
let res = RMS [1.0..10.0]</syntaxhighlight>
Line 797: Line 858:


=={{header|Factor}}==
=={{header|Factor}}==
<syntaxhighlight lang=factor>: root-mean-square ( seq -- mean )
<syntaxhighlight lang="factor">: root-mean-square ( seq -- mean )
[ [ sq ] map-sum ] [ length ] bi / sqrt ;</syntaxhighlight>
[ [ sq ] map-sum ] [ length ] bi / sqrt ;</syntaxhighlight>


Line 804: Line 865:


=={{header|Fantom}}==
=={{header|Fantom}}==
<syntaxhighlight lang=fantom>class Main
<syntaxhighlight lang="fantom">class Main
{
{
static Float averageRms (Float[] nums)
static Float averageRms (Float[] nums)
Line 822: Line 883:


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>: rms ( faddr len -- frms )
<syntaxhighlight lang="forth">: rms ( faddr len -- frms )
dup >r 0e
dup >r 0e
floats bounds do
floats bounds do
Line 834: Line 895:
=={{header|Fortran}}==
=={{header|Fortran}}==
Assume <math> x </math> stored in array x.
Assume <math> x </math> stored in array x.
<syntaxhighlight lang=Fortran>print *,sqrt( sum(x**2)/size(x) )</syntaxhighlight>
<syntaxhighlight lang="fortran">print *,sqrt( sum(x**2)/size(x) )</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
' FB 1.05.0 Win64


Line 867: Line 928:
=={{header|Futhark}}==
=={{header|Futhark}}==


<syntaxhighlight lang=Futhark>
<syntaxhighlight lang="futhark">
import "futlib/math"
import "futlib/math"


Line 875: Line 936:


=={{header|GEORGE}}==
=={{header|GEORGE}}==
<syntaxhighlight lang=GEORGE>
<syntaxhighlight lang="george">
1, 10 rep (i)
1, 10 rep (i)
i i | (v) ;
i i | (v) ;
Line 891: Line 952:


=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 913: Line 974:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<syntaxhighlight lang=groovy>def quadMean = { list ->
<syntaxhighlight lang="groovy">def quadMean = { list ->
list == null \
list == null \
? null \
? null \
Line 921: Line 982:
}</syntaxhighlight>
}</syntaxhighlight>
Test:
Test:
<syntaxhighlight lang=groovy>def list = 1..10
<syntaxhighlight lang="groovy">def list = 1..10
def Q = quadMean(list)
def Q = quadMean(list)
println """
println """
Line 933: Line 994:
=={{header|Haskell}}==
=={{header|Haskell}}==
Given the <code>mean</code> function defined in [[Averages/Pythagorean means]]:
Given the <code>mean</code> function defined in [[Averages/Pythagorean means]]:
<syntaxhighlight lang=haskell>main = print $ mean 2 [1 .. 10]</syntaxhighlight>
<syntaxhighlight lang="haskell">main = print $ mean 2 [1 .. 10]</syntaxhighlight>


Or, writing a naive '''mean''' of our own, (but see https://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/):
Or, writing a naive '''mean''' of our own, (but see https://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/):


<syntaxhighlight lang=haskell>import Data.List (genericLength)
<syntaxhighlight lang="haskell">import Data.List (genericLength)


rootMeanSquare :: [Double] -> Double
rootMeanSquare :: [Double] -> Double
Line 948: Line 1,009:


=={{header|HicEst}}==
=={{header|HicEst}}==
<syntaxhighlight lang=HicEst>sum = 0
<syntaxhighlight lang="hicest">sum = 0
DO i = 1, 10
DO i = 1, 10
sum = sum + i^2
sum = sum + i^2
Line 956: Line 1,017:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every put(x := [], 1 to 10)
every put(x := [], 1 to 10)
writes("x := [ "); every writes(!x," "); write("]")
writes("x := [ "); every writes(!x," "); write("]")
Line 963: Line 1,024:




<syntaxhighlight lang=Icon>procedure qmean(L[]) #: quadratic mean
<syntaxhighlight lang="icon">procedure qmean(L[]) #: quadratic mean
local m
local m
if *L = 0 then fail
if *L = 0 then fail
Line 971: Line 1,032:


=={{header|Io}}==
=={{header|Io}}==
<syntaxhighlight lang=Io>rms := method (figs, (figs map(** 2) reduce(+) / figs size) sqrt)
<syntaxhighlight lang="io">rms := method (figs, (figs map(** 2) reduce(+) / figs size) sqrt)


rms( Range 1 to(10) asList ) println</syntaxhighlight>
rms( Range 1 to(10) asList ) println</syntaxhighlight>
Line 977: Line 1,038:
=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<syntaxhighlight lang=j>rms=: (+/ % #)&.:*:</syntaxhighlight>
<syntaxhighlight lang="j">rms=: (+/ % #)&.:*:</syntaxhighlight>


'''Example Usage:'''
'''Example Usage:'''
<syntaxhighlight lang=j> rms 1 + i. 10
<syntaxhighlight lang="j"> rms 1 + i. 10
6.20484</syntaxhighlight>
6.20484</syntaxhighlight>
<code>*:</code> means [http://jsoftware.com/help/dictionary/d112.htm square]
<code>*:</code> means [http://jsoftware.com/help/dictionary/d112.htm square]
Line 989: Line 1,050:


=={{header|Java}}==
=={{header|Java}}==
<syntaxhighlight lang=java>public class RootMeanSquare {
<syntaxhighlight lang="java">public class RootMeanSquare {


public static double rootMeanSquare(double... nums) {
public static double rootMeanSquare(double... nums) {
Line 1,010: Line 1,071:
{{works with|JavaScript|1.8}}
{{works with|JavaScript|1.8}}
{{works with|Firefox|3.0}}
{{works with|Firefox|3.0}}
<syntaxhighlight lang=javascript>function root_mean_square(ary) {
<syntaxhighlight lang="javascript">function root_mean_square(ary) {
var sum_of_squares = ary.reduce(function(s,x) {return (s + x*x)}, 0);
var sum_of_squares = ary.reduce(function(s,x) {return (s + x*x)}, 0);
return Math.sqrt(sum_of_squares / ary.length);
return Math.sqrt(sum_of_squares / ary.length);
Line 1,020: Line 1,081:
===ES6===
===ES6===


<syntaxhighlight lang=JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';
Line 1,044: Line 1,105:
=={{header|jq}}==
=={{header|jq}}==
The following filter returns ''null'' if given an empty array:
The following filter returns ''null'' if given an empty array:
<syntaxhighlight lang=jq>def rms: length as $length
<syntaxhighlight lang="jq">def rms: length as $length
| if $length == 0 then null
| if $length == 0 then null
else map(. * .) | add | sqrt / $length
else map(. * .) | add | sqrt / $length
end ;</syntaxhighlight>With this definition, the following program would compute the rms of each array in a file or stream of numeric arrays:<syntaxhighlight lang=jq>rms</syntaxhighlight>
end ;</syntaxhighlight>With this definition, the following program would compute the rms of each array in a file or stream of numeric arrays:<syntaxhighlight lang="jq">rms</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
There are a variety of ways to do this via built-in functions in Julia, given an array <code>A = [1:10]</code> of values. The formula can be implemented directly as:
There are a variety of ways to do this via built-in functions in Julia, given an array <code>A = [1:10]</code> of values. The formula can be implemented directly as:
<syntaxhighlight lang=julia>sqrt(sum(A.^2.) / length(A))</syntaxhighlight>
<syntaxhighlight lang="julia">sqrt(sum(A.^2.) / length(A))</syntaxhighlight>
or shorter with using Statistics (and as spoken: root-mean-square)
or shorter with using Statistics (and as spoken: root-mean-square)
<syntaxhighlight lang=julia>sqrt(mean(A.^2.))</syntaxhighlight>
<syntaxhighlight lang="julia">sqrt(mean(A.^2.))</syntaxhighlight>
or the implicit allocation of a new array by <code>A.^2.</code> can be avoided by using <code>sum</code> as a higher-order function: <syntaxhighlight lang=julia>sqrt(sum(x -> x*x, A) / length(A))</syntaxhighlight>
or the implicit allocation of a new array by <code>A.^2.</code> can be avoided by using <code>sum</code> as a higher-order function: <syntaxhighlight lang="julia">sqrt(sum(x -> x*x, A) / length(A))</syntaxhighlight>
One can also use an explicit loop for near-C performance
One can also use an explicit loop for near-C performance
<syntaxhighlight lang=julia>
<syntaxhighlight lang="julia">
function rms(A)
function rms(A)
s = 0.0
s = 0.0
Line 1,065: Line 1,126:
end
end
</syntaxhighlight>
</syntaxhighlight>
Potentially even better is to use the built-in <code>norm</code> function, which computes the square root of the sum of the squares of the entries of <code>A</code> in a way that avoids the possibility of spurious floating-point overflow (if the entries of <code>A</code> are so large that they may overflow if squared): <syntaxhighlight lang=julia>norm(A) / sqrt(length(A))</syntaxhighlight>
Potentially even better is to use the built-in <code>norm</code> function, which computes the square root of the sum of the squares of the entries of <code>A</code> in a way that avoids the possibility of spurious floating-point overflow (if the entries of <code>A</code> are so large that they may overflow if squared): <syntaxhighlight lang="julia">norm(A) / sqrt(length(A))</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang=K>
<syntaxhighlight lang="k">
rms:{_sqrt (+/x^2)%#x}
rms:{_sqrt (+/x^2)%#x}
rms 1+!10
rms 1+!10
Line 1,075: Line 1,136:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang=scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun quadraticMean(vector: Array<Double>) : Double {
fun quadraticMean(vector: Array<Double>) : Double {
Line 1,091: Line 1,152:
Quadratic mean of numbers 1 to 10 is 6.2048368229954285
Quadratic mean of numbers 1 to 10 is 6.2048368229954285
</pre>
</pre>

=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def rms
{lambda {:n}
{sqrt
{/ {+ {S.map {lambda {:i} {* :i :i}}
{S.serie 1 :n}}}
:n}}}}
-> rms

{rms 10}
-> 6.2048368229954285
</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso>define rms(a::staticarray)::decimal => {
<syntaxhighlight lang="lasso">define rms(a::staticarray)::decimal => {
return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size))
return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size))
}
}
Line 1,102: Line 1,177:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>' [RC] Averages/Root mean square
<syntaxhighlight lang="lb">' [RC] Averages/Root mean square


SourceList$ ="1 2 3 4 5 6 7 8 9 10"
SourceList$ ="1 2 3 4 5 6 7 8 9 10"
Line 1,130: Line 1,205:


=={{header|Logo}}==
=={{header|Logo}}==
<syntaxhighlight lang=logo>to rms :v
<syntaxhighlight lang="logo">to rms :v
output sqrt quotient (apply "sum map [? * ?] :v) count :v
output sqrt quotient (apply "sum map [? * ?] :v) count :v
end
end
Line 1,137: Line 1,212:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end
<syntaxhighlight lang="lua">function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end
function rms(t) return (sumsq(unpack(t)) / #t)^.5 end
function rms(t) return (sumsq(unpack(t)) / #t)^.5 end


Line 1,143: Line 1,218:


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang=Maple>y := [ seq(1..10) ]:
<syntaxhighlight lang="maple">y := [ seq(1..10) ]:
RMS := proc( x )
RMS := proc( x )
return sqrt( Statistics:-Mean( x ^~ 2 ) );
return sqrt( Statistics:-Mean( x ^~ 2 ) );
Line 1,154: Line 1,229:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>RootMeanSquare@Range[10]</syntaxhighlight>
<syntaxhighlight lang="mathematica">RootMeanSquare@Range[10]</syntaxhighlight>
The above will give the precise solution <math>\sqrt{\frac{77}{2}}</math>, to downgrade to 6.20484, use '<code>10.</code>' to imply asking for numeric solution, or append '<code>//N</code>' after the whole expression.
The above will give the precise solution <math>\sqrt{\frac{77}{2}}</math>, to downgrade to 6.20484, use '<code>10.</code>' to imply asking for numeric solution, or append '<code>//N</code>' after the whole expression.


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<syntaxhighlight lang=MATLAB>function rms = quadraticMean(list)
<syntaxhighlight lang="matlab">function rms = quadraticMean(list)
rms = sqrt(mean(list.^2));
rms = sqrt(mean(list.^2));
end</syntaxhighlight>
end</syntaxhighlight>
Solution:
Solution:
<syntaxhighlight lang=MATLAB>>> quadraticMean((1:10))
<syntaxhighlight lang="matlab">>> quadraticMean((1:10))


ans =
ans =
Line 1,169: Line 1,244:


=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight lang=maxima>L: makelist(i, i, 10)$
<syntaxhighlight lang="maxima">L: makelist(i, i, 10)$


rms(L) := sqrt(lsum(x^2, x, L)/length(L))$
rms(L) := sqrt(lsum(x^2, x, L)/length(L))$
Line 1,176: Line 1,251:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<syntaxhighlight lang=MAXScript>
<syntaxhighlight lang="maxscript">
fn RMS arr =
fn RMS arr =
(
(
Line 1,185: Line 1,260:
</syntaxhighlight>
</syntaxhighlight>
Output:
Output:
<syntaxhighlight lang=MAXScript>
<syntaxhighlight lang="maxscript">
rms #{1..10}
rms #{1..10}
6.20484
6.20484
Line 1,191: Line 1,266:


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.37.0}}
<syntaxhighlight lang=min>(dup *) :sq
<syntaxhighlight lang="min">(((dup *) map sum) keep size / sqrt) ^rms
('sq map sum) :sum-sq
(('sum-sq 'size) => cleave / sqrt) :rms


(1 2 3 4 5 6 7 8 9 10) rms puts!</syntaxhighlight>
(1 2 3 4 5 6 7 8 9 10) rms puts!</syntaxhighlight>
{{out}}
{{out}}
<pre>6.204836822995428</pre>
<pre>
6.204836822995429
</pre>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>0 П0 П1 С/П x^2 ИП0 x^2 ИП1 *
<syntaxhighlight lang="text">0 П0 П1 С/П x^2 ИП0 x^2 ИП1 *
+ ИП1 1 + П1 / КвКор П0 БП
+ ИП1 1 + П1 / КвКор П0 БП
03</syntaxhighlight>
03</syntaxhighlight>
Line 1,213: Line 1,284:
=={{header|Morfa}}==
=={{header|Morfa}}==
{{trans|D}}
{{trans|D}}
<syntaxhighlight lang=morfa>
<syntaxhighlight lang="morfa">
import morfa.base;
import morfa.base;
import morfa.functional.base;
import morfa.functional.base;
Line 1,235: Line 1,306:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using System.Math;
using System.Math;
Line 1,254: Line 1,325:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,276: Line 1,347:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>from math import sqrt, sum
<syntaxhighlight lang="nim">from math import sqrt, sum
from sequtils import mapIt
from sequtils import mapIt
Line 1,289: Line 1,360:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon-2
Oxford Oberon-2
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE QM;
MODULE QM;
IMPORT ML := MathL, Out;
IMPORT ML := MathL, Out;
Line 1,321: Line 1,392:


=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Hello {
class Hello {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 1,341: Line 1,412:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>let rms a =
<syntaxhighlight lang="ocaml">let rms a =
sqrt (Array.fold_left (fun s x -> s +. x*.x) 0.0 a /.
sqrt (Array.fold_left (fun s x -> s +. x*.x) 0.0 a /.
float_of_int (Array.length a))
float_of_int (Array.length a))
Line 1,351: Line 1,422:
=={{header|Oforth}}==
=={{header|Oforth}}==


<syntaxhighlight lang=Oforth>10 seq map(#sq) sum 10.0 / sqrt .</syntaxhighlight>
<syntaxhighlight lang="oforth">10 seq map(#sq) sum 10.0 / sqrt .</syntaxhighlight>


{{out}}
{{out}}
Line 1,359: Line 1,430:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx>call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
<syntaxhighlight lang="oorexx">call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testAverage .array~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)
Line 1,392: Line 1,463:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
fun {Square X} X*X end
fun {Square X} X*X end


Line 1,410: Line 1,481:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
General RMS calculation:
General RMS calculation:
<syntaxhighlight lang=parigp>RMS(v)={
<syntaxhighlight lang="parigp">RMS(v)={
sqrt(sum(i=1,#v,v[i]^2)/#v)
sqrt(sum(i=1,#v,v[i]^2)/#v)
};
};
Line 1,417: Line 1,488:


Specific functions for the first ''n'' positive integers:
Specific functions for the first ''n'' positive integers:
<syntaxhighlight lang=parigp>RMS_first(n)={
<syntaxhighlight lang="parigp">RMS_first(n)={
sqrt((n+1)*(2*n+1)/6)
sqrt((n+1)*(2*n+1)/6)
};
};
Line 1,425: Line 1,496:


=={{header|Perl}}==
=={{header|Perl}}==
<syntaxhighlight lang=perl>use v5.10.0;
<syntaxhighlight lang="perl">use v5.10.0;
sub rms
sub rms
{
{
Line 1,436: Line 1,507:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">rms</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">rms</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">sqsum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">sqsum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 1,453: Line 1,524:
Alternative, same output<br>
Alternative, same output<br>
You could make this a one-liner, for no gain and making it harder to debug - an explicitly named intermediate such as sqsum adds no additional overhead compared to the un-named hidden temporary variable the compiler would otherwise use anyway, and of course sqsum can be examined/verified to pinpoint any error more effectively. The last (commented-out) line also removes the function call, but of course it has also removed every last descriptive hint of what it is supposed to be doing as well.
You could make this a one-liner, for no gain and making it harder to debug - an explicitly named intermediate such as sqsum adds no additional overhead compared to the un-named hidden temporary variable the compiler would otherwise use anyway, and of course sqsum can be examined/verified to pinpoint any error more effectively. The last (commented-out) line also removes the function call, but of course it has also removed every last descriptive hint of what it is supposed to be doing as well.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">rms</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">rms</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">sqsum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}))</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">sqsum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}))</span>
Line 1,463: Line 1,534:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti>def rms
<syntaxhighlight lang="phixmonti">def rms
0 swap
0 swap
len for
len for
Line 1,479: Line 1,550:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=PHP><?php
<syntaxhighlight lang="php"><?php
// Created with PHP 7.0
// Created with PHP 7.0


Line 1,503: Line 1,574:
{{trans|Prolog}}
{{trans|Prolog}}
{{works with|Picat}}
{{works with|Picat}}
<syntaxhighlight lang=Picat>
<syntaxhighlight lang="picat">
rms(Xs) = Y =>
rms(Xs) = Y =>
Sum = sum_of_squares(Xs),
Sum = sum_of_squares(Xs),
Line 1,525: Line 1,596:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(scl 5)
<syntaxhighlight lang="picolisp">(scl 5)


(let Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0)
(let Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0)
Line 1,541: Line 1,612:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=PL/I> atest: Proc Options(main);
<syntaxhighlight lang="pl/i"> atest: Proc Options(main);
declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10);
declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10);
declare (n,RMS) Dec Float(15);
declare (n,RMS) Dec Float(15);
Line 1,552: Line 1,623:


=={{header|PostScript}}==
=={{header|PostScript}}==
<syntaxhighlight lang=postscript>/findrms{
<syntaxhighlight lang="postscript">/findrms{
/x exch def
/x exch def
/sum 0 def
/sum 0 def
Line 1,573: Line 1,644:
</pre>
</pre>
{{libheader|initlib}}
{{libheader|initlib}}
<syntaxhighlight lang=postscript>[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt</syntaxhighlight>
<syntaxhighlight lang="postscript">[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt</syntaxhighlight>


=={{header|Potion}}==
=={{header|Potion}}==
<syntaxhighlight lang=Potion>rms = (series) :
<syntaxhighlight lang="potion">rms = (series) :
total = 0.0
total = 0.0
series each (x): total += x * x.
series each (x): total += x * x.
Line 1,587: Line 1,658:


=={{header|Powerbuilder}}==
=={{header|Powerbuilder}}==
<syntaxhighlight lang=powerbuilder>long ll_x, ll_y, ll_product
<syntaxhighlight lang="powerbuilder">long ll_x, ll_y, ll_product
decimal ld_rms
decimal ld_rms


Line 1,601: Line 1,672:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell>function get-rms([float[]]$nums){
<syntaxhighlight lang="powershell">function get-rms([float[]]$nums){
$sqsum=$nums | foreach-object { $_*$_} | measure-object -sum | select-object -expand Sum
$sqsum=$nums | foreach-object { $_*$_} | measure-object -sum | select-object -expand Sum
return [math]::sqrt($sqsum/$nums.count)
return [math]::sqrt($sqsum/$nums.count)
Line 1,609: Line 1,680:


=={{header|Processing}}==
=={{header|Processing}}==
<syntaxhighlight lang=processing>void setup() {
<syntaxhighlight lang="processing">void setup() {
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print(rms(numbers));
print(rms(numbers));
Line 1,627: Line 1,698:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|GNU Prolog}}
{{works with|GNU Prolog}}
<syntaxhighlight lang=Prolog>
<syntaxhighlight lang="prolog">
:- initialization(main).
:- initialization(main).


Line 1,652: Line 1,723:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>NewList MyList() ; To hold a unknown amount of numbers to calculate
<syntaxhighlight lang="purebasic">NewList MyList() ; To hold a unknown amount of numbers to calculate


If OpenConsole()
If OpenConsole()
Line 1,682: Line 1,753:
=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3}}
{{works with|Python|3}}
<syntaxhighlight lang=Python>>>> from math import sqrt
<syntaxhighlight lang="python">>>> from math import sqrt
>>> def qmean(num):
>>> def qmean(num):
return sqrt(sum(n*n for n in num)/len(num))
return sqrt(sum(n*n for n in num)/len(num))
Line 1,694: Line 1,765:


Alternatively in terms of '''reduce''':
Alternatively in terms of '''reduce''':
<syntaxhighlight lang=python>from functools import (reduce)
<syntaxhighlight lang="python">from functools import (reduce)
from math import (sqrt)
from math import (sqrt)


Line 1,710: Line 1,781:


=={{header|Qi}}==
=={{header|Qi}}==
<syntaxhighlight lang=qi>(define rms
<syntaxhighlight lang="qi">(define rms
R -> (sqrt (/ (APPLY + (MAPCAR * R R)) (length R))))</syntaxhighlight>
R -> (sqrt (/ (APPLY + (MAPCAR * R R)) (length R))))</syntaxhighlight>


Line 1,718: Line 1,789:
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.


<syntaxhighlight lang=Quackery>[ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery">[ $ "bigrat.qky" loadfile ] now!


[ [] swap
[ [] swap
Line 1,756: Line 1,827:


The following function works for any vector x:
The following function works for any vector x:
<syntaxhighlight lang=rsplus>RMS <- function(x, na.rm = F) sqrt(mean(x^2, na.rm = na.rm))
<syntaxhighlight lang="rsplus">RMS <- function(x, na.rm = F) sqrt(mean(x^2, na.rm = na.rm))


RMS(1:10)
RMS(1:10)
Line 1,768: Line 1,839:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=Racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define (rms nums)
(define (rms nums)
Line 1,776: Line 1,847:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)

{{works with|Rakudo|2015.12}}
<syntaxhighlight lang=perl6>sub rms(*@nums) { sqrt [+](@nums X** 2) / @nums }
<syntaxhighlight lang="raku" line>sub rms(*@nums) { sqrt ([+] @nums X** 2) / @nums }


say rms 1..10;</syntaxhighlight>
say rms 1..10;</syntaxhighlight>


Here's a slightly more concise version, albeit arguably less readable:
Here's a slightly more concise version, albeit arguably less readable:
<syntaxhighlight lang=perl6>sub rms { sqrt @_ R/ [+] @_ X** 2 }</syntaxhighlight>
<syntaxhighlight lang="raku" line>sub rms { sqrt @_ R/ [+] @_ X** 2 }</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,792: Line 1,863:
<br>calculation as well as a reasonable attempt at providing a first-guess square root by essentially halving
<br>calculation as well as a reasonable attempt at providing a first-guess square root by essentially halving
<br>the number using logarithmic (base ten) arithmetic.
<br>the number using logarithmic (base ten) arithmetic.
<syntaxhighlight lang=rexx>/*REXX program computes and displays the root mean square (RMS) of a number sequence. */
<syntaxhighlight lang="rexx">/*REXX program computes and displays the root mean square (RMS) of a number sequence. */
parse arg nums digs show . /*obtain the optional arguments from CL*/
parse arg nums digs show . /*obtain the optional arguments from CL*/
if nums=='' | nums=="," then nums=10 /*Not specified? Then use the default.*/
if nums=='' | nums=="," then nums=10 /*Not specified? Then use the default.*/
Line 1,817: Line 1,888:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
nums = [1,2,3,4,5,6,7,8,9,10]
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
sum = 0
Line 1,830: Line 1,901:
return x
return x
</syntaxhighlight>
</syntaxhighlight>

=={{header|RPL}}==
≪ LIST→ → n
≪ 0 1 n '''START''' SWAP SQ + '''NEXT'''
n / √
≫ ≫ '<span style="color:blue">RMS</span>' STO

{ 1 2 3 4 5 6 7 8 9 10 } <span style="color:blue">RMS</span>
{{out}}
<pre>
1: 6.204836823
</pre>
{{works with|HP|48G}}
≪ DUP ≪ SQ + ≫ STREAM SWAP SIZE / √
≫ '<span style="color:blue">RMS</span>' STO


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang=ruby>class Array
<syntaxhighlight lang="ruby">class Array
def quadratic_mean
def quadratic_mean
Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
Line 1,847: Line 1,933:


and a non object-oriented solution:
and a non object-oriented solution:
<syntaxhighlight lang=ruby>def rms(seq)
<syntaxhighlight lang="ruby">def rms(seq)
Math.sqrt(seq.sum{|x| x*x}.fdiv(seq.size) )
Math.sqrt(seq.sum{|x| x*x}.fdiv(seq.size) )
end
end
Line 1,853: Line 1,939:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=runbasic>valueList$ = "1 2 3 4 5 6 7 8 9 10"
<syntaxhighlight lang="runbasic">valueList$ = "1 2 3 4 5 6 7 8 9 10"
while word$(valueList$,i +1) <> "" ' grab values from list
while word$(valueList$,i +1) <> "" ' grab values from list
thisValue = val(word$(valueList$,i +1)) ' turn values into numbers
thisValue = val(word$(valueList$,i +1)) ' turn values into numbers
Line 1,867: Line 1,953:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>fn root_mean_square(vec: Vec<i32>) -> f32 {
<syntaxhighlight lang="rust">fn root_mean_square(vec: Vec<i32>) -> f32 {
let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
Line 1,888: Line 1,974:
built-in syntax.
built-in syntax.


<syntaxhighlight lang=S-lang>define rms(arr)
<syntaxhighlight lang="s-lang">define rms(arr)
{
{
return sqrt(sum(sqr(arr)) / length(arr));
return sqrt(sum(sqr(arr)) / length(arr));
Line 1,896: Line 1,982:


=={{header|Sather}}==
=={{header|Sather}}==
<syntaxhighlight lang=sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
-- irrms stands for Integer Ranged RMS
-- irrms stands for Integer Ranged RMS
irrms(i, f:INT):FLT
irrms(i, f:INT):FLT
Line 1,914: Line 2,000:


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
<syntaxhighlight lang=basic>
<syntaxhighlight lang="basic">
var n, sqsum, sqmean, rms = real
var n, sqsum, sqmean, rms = real
sqsum = 0
sqsum = 0
Line 1,932: Line 2,018:


=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=scala>def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size)
<syntaxhighlight lang="scala">def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size)
println(rms(1 to 10))</syntaxhighlight>
println(rms(1 to 10))</syntaxhighlight>
{{out}}
{{out}}
Line 1,938: Line 2,024:


=={{header|Scheme}}==
=={{header|Scheme}}==
<syntaxhighlight lang=scheme>(define (rms nums)
<syntaxhighlight lang="scheme">(define (rms nums)
(sqrt (/ (apply + (map * nums nums))
(sqrt (/ (apply + (map * nums nums))
(length nums))))
(length nums))))
Line 1,947: Line 2,033:


=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
include "math.s7i";
include "math.s7i";
Line 1,973: Line 2,059:
=={{header|Shen}}==
=={{header|Shen}}==
{{works with|shen-scheme|0.17}}
{{works with|shen-scheme|0.17}}
<syntaxhighlight lang=Shen>(declare scm.sqrt [number --> number])
<syntaxhighlight lang="shen">(declare scm.sqrt [number --> number])


(tc +)
(tc +)
Line 2,001: Line 2,087:


=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight lang=ruby>func rms(a) {
<syntaxhighlight lang="ruby">func rms(a) {
sqrt(a.map{.**2}.sum / a.len)
sqrt(a.map{.**2}.sum / a.len)
}
}
Line 2,008: Line 2,094:


Using hyper operators, we can write it as:
Using hyper operators, we can write it as:
<syntaxhighlight lang=ruby>func rms(a) { a »**» 2 «+» / a.len -> sqrt }</syntaxhighlight>
<syntaxhighlight lang="ruby">func rms(a) { a »**» 2 «+» / a.len -> sqrt }</syntaxhighlight>


{{out}}
{{out}}
Line 2,014: Line 2,100:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<syntaxhighlight lang=smalltalk>(((1 to: 10) inject: 0 into: [ :s :n | n*n + s ]) / 10) sqrt.</syntaxhighlight>
<syntaxhighlight lang="smalltalk">(((1 to: 10) inject: 0 into: [ :s :n | n*n + s ]) / 10) sqrt.</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 2,020: Line 2,106:
{{works with|CSnobol}}
{{works with|CSnobol}}
There is no built-in sqrt( ) function in Snobol4+.
There is no built-in sqrt( ) function in Snobol4+.
<syntaxhighlight lang=SNOBOL4> define('rms(a)i,ssq') :(rms_end)
<syntaxhighlight lang="snobol4"> define('rms(a)i,ssq') :(rms_end)
rms i = i + 1; ssq = ssq + (a<i> * a<i>) :s(rms)
rms i = i + 1; ssq = ssq + (a<i> * a<i>) :s(rms)
rms = sqrt(1.0 * ssq / prototype(a)) :(return)
rms = sqrt(1.0 * ssq / prototype(a)) :(return)
Line 2,032: Line 2,118:
{{out}}
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 -> 6.20483682</pre>
<pre>1 2 3 4 5 6 7 8 9 10 -> 6.20483682</pre>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "calcrms" )
@( description, "Compute the Root mean square of the numbers 1..10." )
@( description, "The root mean square is also known by its initial RMS (or rms), and as the" )
@( description, "quadratic mean. The RMS is calculated as the mean of the squares of the" )
@( description, "numbers, square-rooted" )
@( see_also, "http://rosettacode.org/wiki/Averages/Root_mean_square" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure calcrms is
type float_arr is array(1..10) of float;
list : constant float_arr := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);
total: float := 0.0;
rms : float;
begin
for p in arrays.first(list)..arrays.last(list) loop
total := @ + list(p)**2;
end loop;
rms := numerics.sqrt( total / float(arrays.length(list)));
? rms;
end calcrms;</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang=sml>fun rms(v: real vector) =
<syntaxhighlight lang="sml">fun rms(v: real vector) =
let
let
val v' = Vector.map (fn x => x*x) v
val v' = Vector.map (fn x => x*x) v
Line 2,049: Line 2,162:
Compute the RMS of a variable and return the result in r(rms).
Compute the RMS of a variable and return the result in r(rms).


<syntaxhighlight lang=stata>program rms, rclass
<syntaxhighlight lang="stata">program rms, rclass
syntax varname(numeric) [if] [in]
syntax varname(numeric) [if] [in]
tempvar x
tempvar x
Line 2,059: Line 2,172:
'''Example'''
'''Example'''


<syntaxhighlight lang=stata>clear
<syntaxhighlight lang="stata">clear
set obs 20
set obs 20
gen x=rnormal()
gen x=rnormal()
Line 2,073: Line 2,186:
=={{header|Swift}}==
=={{header|Swift}}==


<syntaxhighlight lang=swift>extension Collection where Element: FloatingPoint {
<syntaxhighlight lang="swift">extension Collection where Element: FloatingPoint {
@inlinable
@inlinable
public func rms() -> Element {
public func rms() -> Element {
Line 2,088: Line 2,201:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<syntaxhighlight lang=tcl>proc qmean list {
<syntaxhighlight lang="tcl">proc qmean list {
set sum 0.0
set sum 0.0
foreach value $list { set sum [expr {$sum + $value**2}] }
foreach value $list { set sum [expr {$sum + $value**2}] }
Line 2,102: Line 2,215:
=={{header|Ursala}}==
=={{header|Ursala}}==
using the <code>mean</code> function among others from the <code>flo</code> library
using the <code>mean</code> function among others from the <code>flo</code> library
<syntaxhighlight lang=Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat
#import flo
#import flo


Line 2,115: Line 2,228:
=={{header|Vala}}==
=={{header|Vala}}==
Valac probably needs to have the flag "-X -lm" added to include the C Math library.
Valac probably needs to have the flag "-X -lm" added to include the C Math library.
<syntaxhighlight lang=vala>double rms(double[] list){
<syntaxhighlight lang="vala">double rms(double[] list){
double sum_squares = 0;
double sum_squares = 0;
double mean;
double mean;
Line 2,141: Line 2,254:
=={{header|VBA}}==
=={{header|VBA}}==
Using Excel VBA
Using Excel VBA
<syntaxhighlight lang=vb>Private Function root_mean_square(s() As Variant) As Double
<syntaxhighlight lang="vb">Private Function root_mean_square(s() As Variant) As Double
For i = 1 To UBound(s)
For i = 1 To UBound(s)
s(i) = s(i) ^ 2
s(i) = s(i) ^ 2
Line 2,153: Line 2,266:
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>
Without using Excel worksheetfunction:
Without using Excel worksheetfunction:
<syntaxhighlight lang=vb>Function rms(iLow As Integer, iHigh As Integer)
<syntaxhighlight lang="vb">Function rms(iLow As Integer, iHigh As Integer)
Dim i As Integer
Dim i As Integer
If iLow > iHigh Then
If iLow > iHigh Then
Line 2,176: Line 2,289:
</pre>
</pre>


=={{header|Vlang}}==
=={{header|V (Vlang)}}==
<syntaxhighlight lang=vlang>import math
<syntaxhighlight lang="v (vlang)">import math
fn main() {
fn main() {
Line 2,194: Line 2,307:


=={{header|Wortel}}==
=={{header|Wortel}}==
<syntaxhighlight lang=wortel>@let {
<syntaxhighlight lang="wortel">@let {
; using a composition and a fork (like you would do in J)
; using a composition and a fork (like you would do in J)
rms1 ^(@sqrt @(@sum / #) *^@sq)
rms1 ^(@sqrt @(@sum / #) *^@sq)
Line 2,210: Line 2,323:


=={{header|Wren}}==
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript>var rms = ((1..10).reduce(0) { |acc, i| acc + i*i }/10).sqrt
<syntaxhighlight lang="wren">var rms = ((1..10).reduce(0) { |acc, i| acc + i*i }/10).sqrt
System.print(rms)</syntaxhighlight>
System.print(rms)</syntaxhighlight>


Line 2,219: Line 2,332:


=={{header|XLISP}}==
=={{header|XLISP}}==
<syntaxhighlight lang=lisp>(defun quadratic-mean (xs)
<syntaxhighlight lang="lisp">(defun quadratic-mean (xs)
(sqrt
(sqrt
(/
(/
Line 2,239: Line 2,352:


=={{header|XPL0}}==
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0>code CrLf=9;
<syntaxhighlight lang="xpl0">code CrLf=9;
code real RlOut=48;
code real RlOut=48;
int N;
int N;
Line 2,254: Line 2,367:


=={{header|Yacas}}==
=={{header|Yacas}}==
<syntaxhighlight lang=Yacas>Sqrt(Add((1 .. 10)^2)/10)</syntaxhighlight>
<syntaxhighlight lang="yacas">Sqrt(Add((1 .. 10)^2)/10)</syntaxhighlight>
The above will give the precise solution <math>\sqrt{\frac{77}{2}}</math>, to downgrade to 6.20483682299, surround the expression with '<code>N()</code>'.
The above will give the precise solution <math>\sqrt{\frac{77}{2}}</math>, to downgrade to 6.20483682299, surround the expression with '<code>N()</code>'.


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() }</syntaxhighlight>
<syntaxhighlight lang="zkl">fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() }</syntaxhighlight>
The order in the reduce function is important as it coerces n*n to float.
The order in the reduce function is important as it coerces n*n to float.
<pre>
<pre>

Latest revision as of 10:23, 29 December 2023

Task
Averages/Root mean square
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Compute the   Root mean square   of the numbers 1..10.


The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean.

The RMS is calculated as the mean of the squares of the numbers, square-rooted:



See also



11l

Translation of: Python
F qmean(num)
   R sqrt(sum(num.map(n -> n * n)) / Float(num.len))

print(qmean(1..10))
Output:
6.20484

Action!

INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

BYTE FUNC Equal(REAL POINTER a,b)
  BYTE ARRAY x,y

  x=a y=b
  IF x(0)=y(0) AND x(1)=y(1) AND x(2)=y(2) THEN
    RETURN (1)
  FI
RETURN (0)

PROC Sqrt(REAL POINTER a,b)
  REAL z,half

  IntToReal(0,z)
  ValR("0.5",half)
  
  IF Equal(a,z) THEN
    RealAssign(z,b)
  ELSE
    Power(a,half,b)
  FI
RETURN

PROC Main()
  BYTE i
  REAL x,x2,sum,tmp

  IntToReal(0,sum)
  FOR i=1 TO 10
  DO
    IntToReal(i,x)
    RealMult(x,x,x2)
    RealAdd(sum,x2,tmp)
    RealAssign(tmp,sum)
  OD
  IntToReal(10,x)
  RealDiv(sum,x,tmp)
  Sqrt(tmp,x)

  Put(125) PutE() ;clear screen
  Print("RMS of 1..10 is ")
  PrintRE(x)
RETURN
Output:

Screenshot from Atari 8-bit computer

RMS of 1..10 is 6.20483663

Ada

with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions;
use Ada.Numerics.Elementary_Functions;
procedure calcrms is
	type float_arr is array(1..10) of Float;
	
	function rms(nums : float_arr) return Float is
		sum : Float := 0.0;
		begin
		for p in nums'Range loop
			sum := sum + nums(p)**2;
		end loop;
		return sqrt(sum/Float(nums'Length));
	end rms;

	list : float_arr;
begin
list := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);
put( rms(list) , Exp=>0);
end calcrms;
Output:
 6.20484

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards)
# Define the rms PROCedure & ABS OPerators for LONG... REAL #
MODE RMSFIELD = #LONG...# REAL;
PROC (RMSFIELD)RMSFIELD rms field sqrt = #long...# sqrt;
INT rms field width = #long...# real width;

PROC crude rms = ([]RMSFIELD v)RMSFIELD: (
  RMSFIELD sum := 0;
  FOR i FROM LWB v TO UPB v DO sum +:= v[i]**2 OD;
  rms field sqrt(sum / (UPB v - LWB v + 1))
);
 
PROC rms = ([]RMSFIELD v)RMSFIELD: (
# round off error accumulated at standard precision #
  RMSFIELD sum := 0, round off error:= 0;
  FOR i FROM LWB v TO UPB v DO 
    RMSFIELD org = sum, prod = v[i]**2;
    sum +:= prod;
    round off error +:= sum - org - prod
  OD;
  rms field sqrt((sum - round off error)/(UPB v - LWB v + 1))
);

main: (
  []RMSFIELD one to ten = (1,2,3,4,5,6,7,8,9,10);

  print(("crude rms(one to ten): ", crude rms(one to ten), new line));
  print(("rms(one to ten): ",       rms(one to ten), new line))
)
Output:
crude rms(one to ten): +6.20483682299543e  +0
rms(one to ten): +6.20483682299543e  +0

ALGOL-M

Because ALGOL-M lacks a built-in square root function, we have to supply our own.

BEGIN

DECIMAL FUNCTION SQRT(X);
DECIMAL X;
BEGIN
    DECIMAL R1, R2, TOL;
    TOL := .00001;   % reasonable for most purposes %
    IF X >= 1.0 THEN
       BEGIN
          R1 := X;
          R2 := 1.0;
       END
    ELSE
       BEGIN
          R1 := 1.0;
          R2 := X;
       END;
    WHILE (R1-R2) > TOL DO
        BEGIN
            R1 := (R1+R2) / 2.0;
            R2 := X / R1;
        END;
    SQRT := R1;
END;

COMMENT - MAIN PROGRAM BEGINS HERE;

DECIMAL N, SQSUM, SQMEAN;

SQSUM := 0.0;
FOR N := 1.0 STEP 1.0 UNTIL 10.0 DO
    SQSUM := SQSUM + (N * N);
SQMEAN := SQSUM / (N - 1.0);
WRITE("RMS OF WHOLE NUMBERS 1.0 THROUGH 10.0 =", SQRT(SQMEAN));

END
Output:

Based on the limited precision of the square root function, only the first six decimal places of the output can actually be relied on (but that's more than sufficient for most real world uses).

RMS OF WHOLE NUMBERS 1.0 THROUGH 10.0 = 6.20483683432

ALGOL W

begin
    % computes the root-mean-square of an array of numbers with               %
    % the specified lower bound (lb) and upper bound (ub)                     %
    real procedure rms( real    array numbers ( * )
                      ; integer value lb
                      ; integer value ub
                      ) ;
        begin
            real sum;
            sum := 0;
            for i := lb until ub do sum := sum + ( numbers(i) * numbers(i) );
            sqrt( sum / ( ( ub - lb ) + 1 ) )
        end rms ;

    % test the rms procedure with the numbers 1 to 10                         %
    real array testNumbers( 1 :: 10 );
    for i := 1 until 10 do testNumbers(i) := i;
    r_format := "A"; r_w := 10; r_d := 4; % set fixed point output           %
    write( "rms of 1 .. 10: ", rms( testNumbers, 1, 10 ) );

end.
Output:
rms of 1 .. 10:     6.2048  

APL

 rms{((+/*2)÷⍴)*0.5}
 x10

 rms x
6.204836823

AppleScript

Functional

Translation of: JavaScript

( ES6 version )

--------------------- ROOT MEAN SQUARE -------------------

-- rootMeanSquare :: [Num] -> Real
on rootMeanSquare(xs)
    script
        on |λ|(a, x)
            a + x * x
        end |λ|
    end script
    
    (foldl(result, 0, xs) / (length of xs)) ^ (1 / 2)
end rootMeanSquare


--------------------------- TEST -------------------------
on run
    
    rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
    
    -- > 6.204836822995
end run


-------------------- GENERIC FUNCTIONS -------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
6.204836822995

Straightforward

on rootMeanSquare(listOfNumbers)
    script o
        property lst : listOfNumbers
    end script
    set r to 0.0
    repeat with n in o's lst
        set r to r + (n ^ 2)
    end repeat
    
    return (r / (count o's lst)) ^ 0.5
end rootMeanSquare

rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
Output:
6.204836822995

Integer range alternative

Translation of: AutoHotKey

("Avoiding a loop" solution)

-- RMS of integer range a to b.
on rootMeanSquare(a, b)
	return ((b * (b + 1) * (2 * b + 1) - a * (a - 1) * (2 * a - 1)) / 6 / (b - a + 1)) ^ 0.5
end rootMeanSquare

rootMeanSquare(1, 10)
Output:
6.204836822995

Arturo

rootMeanSquare: function [arr]->
    sqrt (sum map arr 'i -> i^2) // size arr

print rootMeanSquare 1..10
Output:
6.204836822995428

Astro

sqrt(mean(x²))

AutoHotkey

Using a loop

MsgBox, % RMS(1, 10)


;---------------------------------------------------------------------------
RMS(a, b) { ; Root Mean Square of integers a through b
;---------------------------------------------------------------------------
    n := b - a + 1
    Loop, %n%
        Sum += (a + A_Index - 1) ** 2
    Return, Sqrt(Sum / n)
}

Message box shows:

6.204837

Avoiding a loop

Using these equations:
See wp:List of mathematical series

for  :

We can show that:

MsgBox, % RMS(1, 10)


;---------------------------------------------------------------------------
RMS(a, b) { ; Root Mean Square of integers a through b
;---------------------------------------------------------------------------
    Return, Sqrt((b*(b+1)*(2*b+1)-a*(a-1)*(2*a-1))/6/(b-a+1))
}

Message box shows:

6.204837

AWK

#!/usr/bin/awk -f
# computes RMS of the 1st column of a data file
{
    x  = $1;   # value of 1st column
    S += x*x;  
    N++;
}

END {
   print "RMS: ",sqrt(S/N);
}

BASIC

Works with: QBasic

Note that this will work in Visual Basic and the Windows versions of PowerBASIC by simply wrapping the module-level code into the MAIN function, and changing PRINT to MSGBOX.

DIM i(1 TO 10) AS DOUBLE, L0 AS LONG
FOR L0 = 1 TO 10
    i(L0) = L0
NEXT
PRINT STR$(rms#(i()))

FUNCTION rms# (what() AS DOUBLE)
    DIM L0 AS LONG, tmp AS DOUBLE, rt AS DOUBLE
    FOR L0 = LBOUND(what) TO UBOUND(what)
        rt = rt + (what(L0) ^ 2)
    NEXT
    tmp = UBOUND(what) - LBOUND(what) + 1
    rms# = SQR(rt / tmp)
END FUNCTION

See also: BBC BASIC, Liberty BASIC, PureBasic, Run BASIC

Applesoft BASIC

 10 N = 10
 20  FOR I = 1 TO N
 30 S = S + I * I
 40  NEXT
 50 X =  SQR (S / N)
 60  PRINT X
Output:
6.20483683

Craft Basic

precision 8

let n = 10

for i = 1 to n

	let s = s + i * i

next i

print sqrt(s / n)
Output:
6.20483682

IS-BASIC

100 PRINT RMS(10)
110 DEF RMS(N)
120   LET R=0
130   FOR X=1 TO N
140     LET R=R+X^2
150   NEXT
160   LET RMS=SQR(R/N)
170 END DEF

Sinclair ZX81 BASIC

10 FAST
20 LET RMS=0
30 FOR X=1 TO 10
40 LET RMS=RMS+X**2
50 NEXT X
60 LET RMS=SQR (RMS/10)
70 SLOW
80 PRINT RMS
Output:
6.2048368

BBC BASIC

      DIM array(9)
      array() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
      
      PRINT FNrms(array())
      END
      
      DEF FNrms(a()) = MOD(a()) / SQR(DIM(a(),1)+1)

BQN

RMS is a tacit function which computes root mean square.

RMS  √+´×˜÷≠

RMS 1+↕10
6.2048368229954285

Try It!

Another solution is to take the arithmetic mean +´÷≠ under the square (ט) function. Under () squares the arguments, then applies the mean, then inverts the square function.

RMS  (+´÷≠)(ט)

C

#include <stdio.h>
#include <math.h>

double rms(double *v, int n)
{
  int i;
  double sum = 0.0;
  for(i = 0; i < n; i++)
    sum += v[i] * v[i];
  return sqrt(sum / n);
}

int main(void)
{
  double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
  printf("%f\n", rms(v, sizeof(v)/sizeof(double)));
  return 0;
}

C#

using System;

namespace rms
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] x = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine(rootMeanSquare(x));
        }

        private static double rootMeanSquare(int[] x)
        {            
            double sum = 0;
            for (int i = 0; i < x.Length; i++)
            {
                sum += (x[i]*x[i]);
            }
            return Math.Sqrt(sum / x.Length);
        }
    }
}

An alternative method demonstrating the more functional style introduced by LINQ and lambda expressions in C# 3.

Works with: C# version 3
using System;
using System.Collections.Generic;
using System.Linq;

namespace rms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(rootMeanSquare(Enumerable.Range(1, 10)));
        }

        private static double rootMeanSquare(IEnumerable<int> x)
        {
            return Math.Sqrt(x.Average(i => (double)i * i));
        }
    }
}

C++

#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>

int main( ) {
  std::vector<int> numbers ;
  for ( int i = 1 ; i < 11 ; i++ )
    numbers.push_back( i ) ;
  double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.size() ) );
  std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ;
  return 0 ;
}
Output:
The quadratic mean of the numbers 1 .. 10 is 6.20484 !

Clojure

(defn rms [xs]
  (Math/sqrt (/ (reduce + (map #(* % %) xs))
	   (count xs))))

(println (rms (range 1 11)))
Output:
6.2048368229954285

COBOL

Could be written more succinctly, with an inline loop and more COMPUTE statements; but that wouldn't be very COBOLic.

IDENTIFICATION DIVISION.
PROGRAM-ID. QUADRATIC-MEAN-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01  QUADRATIC-MEAN-VARS.
    05 N               PIC 99        VALUE 0.
    05 N-SQUARED       PIC 999.
    05 RUNNING-TOTAL   PIC 999       VALUE 0.
    05 MEAN-OF-SQUARES PIC 99V9(16).
    05 QUADRATIC-MEAN  PIC 9V9(15).
PROCEDURE DIVISION.
CONTROL-PARAGRAPH.
    PERFORM MULTIPLICATION-PARAGRAPH 10 TIMES.
    DIVIDE  RUNNING-TOTAL BY 10 GIVING MEAN-OF-SQUARES.
    COMPUTE QUADRATIC-MEAN = FUNCTION SQRT(MEAN-OF-SQUARES).
    DISPLAY QUADRATIC-MEAN UPON CONSOLE.
    STOP RUN.
MULTIPLICATION-PARAGRAPH.
    ADD      1         TO N.
    MULTIPLY N         BY N GIVING N-SQUARED.
    ADD      N-SQUARED TO RUNNING-TOTAL.
Output:
6.204836822995428

CoffeeScript

Translation of: JavaScript
    root_mean_square = (ary) ->
        sum_of_squares = ary.reduce ((s,x) -> s + x*x), 0
        return Math.sqrt(sum_of_squares / ary.length)
     
    alert root_mean_square([1..10])

Common Lisp

(loop for x from 1 to 10
      for xx = (* x x)
      for n from 1
      summing xx into xx-sum
      finally (return (sqrt (/ xx-sum n))))

Here's a non-iterative solution.

(defun root-mean-square (numbers)
  "Takes a list of numbers, returns their quadratic mean."
  (sqrt
   (/ (apply #'+ (mapcar #'(lambda (x) (* x x)) numbers))
      (length numbers))))

(root-mean-square (loop for i from 1 to 10 collect i))

Crystal

Translation of: Ruby
def rms(seq)
  Math.sqrt(seq.sum { |x| x*x } / seq.size)
end

puts rms (1..10).to_a
Output:
6.2048368229954285

D

import std.stdio, std.math, std.algorithm, std.range;

real rms(R)(R d) pure {
    return sqrt(d.reduce!((a, b) => a + b * b) / real(d.length));
}

void main() {
    writefln("%.19f", iota(1, 11).rms);
}
Output:
6.2048368229954282979

Delphi/Pascal

program AveragesMeanSquare;

{$APPTYPE CONSOLE}

uses Types;

function MeanSquare(aArray: TDoubleDynArray): Double;
var
  lValue: Double;
begin
  Result := 0;

  for lValue in aArray do
    Result := Result + (lValue * lValue);
  if Result > 0 then
    Result := Sqrt(Result / Length(aArray));
end;

begin
  Writeln(MeanSquare(TDoubleDynArray.Create()));
  Writeln(MeanSquare(TDoubleDynArray.Create(1,2,3,4,5,6,7,8,9,10)));
end.

E

Using the same generic mean function as used in pythagorean means:

def makeMean(base, include, finish) {
    return def mean(numbers) {
        var count := 0
        var acc := base
        for x in numbers {
            acc := include(acc, x)
            count += 1
        }
        return finish(acc, count)
    }
}

def RMS := makeMean(0, fn b,x { b+x**2 }, fn acc,n { (acc/n).sqrt() })
? RMS(1..10)
# value: 6.2048368229954285

EasyLang

Translation of: C
func rms v[] .
   for v in v[]
      sum += v * v
   .
   return sqrt (sum / len v[])
.
v[] = [ 1 2 3 4 5 6 7 8 9 10 ]
print rms v[]

EchoLisp

(define (rms xs) 
    (sqrt (// (for/sum ((x xs)) (* x x)) (length xs))))

(rms (range 1 11))
     6.2048368229954285

Elena

Translation of: C#

ELENA 6.x :

import extensions;
import system'routines;
import system'math;
 
extension op
{
    get RootMeanSquare()
        = (self.selectBy::(x => x * x).summarize(Real.new()) / self.Length).sqrt();
}
 
public program()
{
    console.printLine(new Range(1, 10).RootMeanSquare)
}
Output:
6.204836822995

Elixir

defmodule RC do
  def root_mean_square(enum) do
    enum
    |> square
    |> mean
    |> :math.sqrt
  end

  defp mean(enum), do: Enum.sum(enum) / Enum.count(enum)

  defp square(enum), do: (for x <- enum, do: x * x)
end

IO.puts RC.root_mean_square(1..10)
Output:
6.2048368229954285

Emacs Lisp

(defun rms (nums)
  (sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums))
           (float (length nums)))))

(rms (number-sequence 1 10))
Output:
6.2048368229954285

Erlang

rms(Nums) ->
    math:sqrt(lists:foldl(fun(E,S) -> S+E*E end, 0, Nums) / length(Nums)).

rms([1,2,3,4,5,6,7,8,9,10]).
Output:
6.2048368229954285

ERRE

PROGRAM ROOT_MEAN_SQUARE
BEGIN
  N=10
  FOR I=1 TO N DO
     S=S+I*I
  END FOR
  X=SQR(S/N)
  PRINT("Root mean square is";X)
END PROGRAM

You can, obviously, generalize reading data from a DATA line or from a file.

Euphoria

function rms(sequence s)
    atom sum
    if length(s) = 0 then
        return 0
    end if
    sum = 0
    for i = 1 to length(s) do
        sum += power(s[i],2)
    end for
    return sqrt(sum/length(s))
end function

constant s = {1,2,3,4,5,6,7,8,9,10}
? rms(s)
Output:
6.204836823

Excel

Cell reference expression

If values are entered in the cells A1 to A10, the below expression will give the RMS value

=SQRT(SUMSQ($A1:$A10)/COUNT($A1:$A10))

The RMS of [1,10] is then : 6.204836823 ( Actual displayed value 6.204837)

LAMBDA

In Excel builds equipped with the LAMBDA function, we can also rework the cell reference expression above to define a custom function, binding a name like ROOTMEANSQR to it in the workBook Name Manager:

(See LAMBDA: The ultimate Excel worksheet function)

ROOTMEANSQR
=LAMBDA(xs,
    SQRT(SUMSQ(xs)/COUNT(xs))
)

For this test, we assume that the following generic lambda is also bound to the name ENUMFROMTO in the Name Manager:

ENUMFROMTO
=LAMBDA(a,
    LAMBDA(z,
        SEQUENCE(1 + z - a, 1, a, 1)
    )
)
Output:
fx =ROOTMEANSQR( ENUMFROMTO( 1 )( 10 ) )
A B
1 [1..10]
2 Root mean square 6.2048368229954285

F#

Uses a lambda expression and function piping.

let RMS (x:float list) : float = List.map (fun y -> y**2.0) x |> List.average |> System.Math.Sqrt

let res = RMS [1.0..10.0]

Answer (in F# Interactive window):

val res : float = 6.204836823

Factor

: root-mean-square ( seq -- mean )
    [ [ sq ] map-sum ] [ length ] bi / sqrt ;
( scratchpad ) 10 [1,b] root-mean-square .
6.204836822995428

Fantom

class Main
{
  static Float averageRms (Float[] nums)
  {
    if (nums.size == 0) return 0.0f
    Float sum := 0f
    nums.each { sum += it * it }
    return (sum / nums.size.toFloat).sqrt
  }

  public static Void main ()
  {
    a := [1f,2f,3f,4f,5f,6f,7f,8f,9f,10f]
    echo ("RMS Average of $a is: " + averageRms(a))
  }
}

Forth

: rms ( faddr len -- frms )
  dup >r 0e
  floats bounds do
    i f@ fdup f* f+
  float +loop
  r> s>f f/ fsqrt ;

create test 1e f, 2e f, 3e f, 4e f, 5e f, 6e f, 7e f, 8e f, 9e f, 10e f,
test 10 rms f.    \ 6.20483682299543

Fortran

Assume stored in array x.

print *,sqrt( sum(x**2)/size(x) )

FreeBASIC

' FB 1.05.0 Win64

Function QuadraticMean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  Dim As Double sum = 0.0
  For i As Integer = LBound(array) To UBound(array)
    sum += array(i) * array(i)
  Next
  Return Sqr(sum/length)
End Function

Dim vector(1 To 10) As Double
For i As Integer = 1 To 10
  vector(i) = i
Next

Print "Quadratic mean (or RMS) is :"; QuadraticMean(vector())
Print
Print "Press any key to quit the program"
Sleep
Output:
Quadratic mean (or RMS) is : 6.204836822995429

Futhark

import "futlib/math"

fun main(as: [n]f64): f64 =
  f64.sqrt ((reduce (+) 0.0 (map (**2.0) as)) / f64(n))

GEORGE

1, 10 rep (i)
   i i | (v) ;
0
 1, 10 rep (i)
   i dup mult +
   ]
10 div
 sqrt
 print
 6.204836822995428

Go

package main

import (
    "fmt"
    "math"
)

func main() {
    const n = 10
    sum := 0.
    for x := 1.; x <= n; x++ {
        sum += x * x
    }
    fmt.Println(math.Sqrt(sum / n))
}
Output:
6.2048368229954285

Groovy

Solution:

def quadMean = { list ->
    list == null \
        ? null \
        : list.empty \
            ? 0 \
            : ((list.collect { it*it }.sum()) / list.size()) ** 0.5
}

Test:

def list = 1..10
def Q = quadMean(list)
println """
list: ${list}
   Q: ${Q}
"""
Output:
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   Q: 6.2048368229954285

Haskell

Given the mean function defined in Averages/Pythagorean means:

main = print $ mean 2 [1 .. 10]

Or, writing a naive mean of our own, (but see https://donsbot.wordpress.com/2008/06/04/haskell-as-fast-as-c-working-at-a-high-altitude-for-low-level-performance/):

import Data.List (genericLength)

rootMeanSquare :: [Double] -> Double
rootMeanSquare = sqrt . (((/) . foldr ((+) . (^ 2)) 0) <*> genericLength)

main :: IO ()
main = print $ rootMeanSquare [1 .. 10]
Output:
6.2048368229954285

HicEst

sum = 0
DO i = 1, 10
   sum = sum + i^2
ENDDO
WRITE(ClipBoard) "RMS(1..10) = ", (sum/10)^0.5

RMS(1..10) = 6.204836823

Icon and Unicon

procedure main()
every put(x := [], 1 to 10)
writes("x := [ "); every writes(!x," "); write("]")
write("Quadratic mean:",q := qmean!x)
end


procedure qmean(L[])             #: quadratic mean
   local m
   if *L = 0 then fail
   every (m := 0.0) +:= !L^2
   return sqrt(m / *L)
end

Io

rms := method (figs, (figs map(** 2) reduce(+) / figs size) sqrt)

rms( Range 1 to(10) asList ) println

J

Solution:

rms=: (+/ % #)&.:*:

Example Usage:

  rms 1 + i. 10
6.20484

*: means square

(+/ % #) is an idiom for mean.

&.: means under -- in other words, we square numbers, take their average and then use the inverse of square on the result. (see also the page on &. which does basically the same thing but with different granularity -- item at a time instead of everything at once.

Java

public class RootMeanSquare {

    public static double rootMeanSquare(double... nums) {
        double sum = 0.0;
        for (double num : nums)
            sum += num * num;
        return Math.sqrt(sum / nums.length);
    }

    public static void main(String[] args) {
        double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
        System.out.println("The RMS of the numbers from 1 to 10 is " + rootMeanSquare(nums));
    }
}
Output:
The RMS of the numbers from 1 to 10 is 6.2048368229954285

JavaScript

ES5

Works with: JavaScript version 1.8
Works with: Firefox version 3.0
function root_mean_square(ary) {
    var sum_of_squares = ary.reduce(function(s,x) {return (s + x*x)}, 0);
    return Math.sqrt(sum_of_squares / ary.length);
}

print( root_mean_square([1,2,3,4,5,6,7,8,9,10]) ); // ==> 6.2048368229954285


ES6

(() => {
    'use strict';
 
 
    // rootMeanSquare :: [Num] -> Real
    const rootMeanSquare = xs => 
       Math.sqrt(
            xs.reduce(
                (a, x) => (a + x * x),
                0
           ) / xs.length
        );
 
     
    return rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    
     // -> 6.2048368229954285
})();
Output:
6.2048368229954285

jq

The following filter returns null if given an empty array:

def rms: length as $length
  | if $length == 0 then null
    else map(. * .) | add | sqrt / $length
    end ;

With this definition, the following program would compute the rms of each array in a file or stream of numeric arrays:

rms

Julia

There are a variety of ways to do this via built-in functions in Julia, given an array A = [1:10] of values. The formula can be implemented directly as:

sqrt(sum(A.^2.) / length(A))

or shorter with using Statistics (and as spoken: root-mean-square)

sqrt(mean(A.^2.))

or the implicit allocation of a new array by A.^2. can be avoided by using sum as a higher-order function:

sqrt(sum(x -> x*x, A) / length(A))

One can also use an explicit loop for near-C performance

function rms(A)
   s = 0.0
   for a in A
      s += a*a
   end
   return sqrt(s / length(A))
end

Potentially even better is to use the built-in norm function, which computes the square root of the sum of the squares of the entries of A in a way that avoids the possibility of spurious floating-point overflow (if the entries of A are so large that they may overflow if squared):

norm(A) / sqrt(length(A))

K

  rms:{_sqrt (+/x^2)%#x}
  rms 1+!10
6.204837

Kotlin

// version 1.0.5-2

fun quadraticMean(vector: Array<Double>) : Double {
    val sum = vector.sumByDouble { it * it }
    return Math.sqrt(sum / vector.size)
}
   
fun main(args: Array<String>) {
    val vector = Array(10, { (it + 1).toDouble() })
    print("Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}")
}
Output:
Quadratic mean of numbers 1 to 10 is 6.2048368229954285

Lambdatalk

{def rms
 {lambda {:n}
  {sqrt
   {/ {+ {S.map {lambda {:i} {* :i :i}}
                {S.serie 1 :n}}}
      :n}}}}
-> rms

{rms 10}
-> 6.2048368229954285

Lasso

define rms(a::staticarray)::decimal => {
	return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size))
}
rms(generateSeries(1,10)->asStaticArray)
Output:
6.204837

Liberty BASIC

'   [RC] Averages/Root mean square

    SourceList$     ="1 2 3 4 5 6 7 8 9 10"

    '   If saved as an array we'd have to have a flag for last data.
    '   LB has the very useful word$() to read from delimited strings.
    '   The default delimiter is a space character, " ".

    SumOfSquares    =0
    n               =0      '   This holds index to number, and counts number of data.
    data$           ="666"  '   temporary dummy to enter the loop.

    while data$ <>""                                '   we loop until no data left.
        data$           =word$( SourceList$, n +1)  '   first data, as a string
        NewVal          =val( data$)                '   convert string to number
        SumOfSquares    =SumOfSquares +NewVal^2     '   add to existing sum of squares
        n =n +1                                     '   increment number of data items found
    wend

    n =n -1

    print "Supplied data was ";         SourceList$
    print "This contained ";            n; " numbers."
    print "R.M.S. value is ";           ( SumOfSquares /n)^0.5

    end

to rms :v
  output sqrt quotient (apply "sum map [? * ?] :v) count :v
end

show rms iseq 1 10

Lua

function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end
function rms(t) return (sumsq(unpack(t)) / #t)^.5 end

print(rms{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

Maple

y := [ seq(1..10) ]:
RMS := proc( x )
    return sqrt( Statistics:-Mean( x ^~ 2 ) );
end proc:
RMS( y );
Output:
6.20483682299543

Mathematica / Wolfram Language

RootMeanSquare@Range[10]

The above will give the precise solution , to downgrade to 6.20484, use '10.' to imply asking for numeric solution, or append '//N' after the whole expression.

MATLAB

function rms = quadraticMean(list)    
    rms = sqrt(mean(list.^2));
end

Solution:

>> quadraticMean((1:10))

ans =

   6.204836822995429

Maxima

L: makelist(i, i, 10)$

rms(L) := sqrt(lsum(x^2, x, L)/length(L))$

rms(L), numer;   /* 6.204836822995429 */

MAXScript

fn RMS arr =
(
	local sumSquared = 0
	for i in arr do sumSquared += i^2
	return (sqrt (sumSquared/arr.count as float))
)

Output:

rms #{1..10}
6.20484

min

Works with: min version 0.37.0
(((dup *) map sum) keep size / sqrt) ^rms

(1 2 3 4 5 6 7 8 9 10) rms puts!
Output:
6.204836822995428

МК-61/52

0	П0	П1	С/П	x^2	ИП0	x^2	ИП1	*
+	ИП1	1	+	П1	/	КвКор	П0	БП
03

Instruction: В/О С/П Number С/П Number ...

Each time you press the С/П on the indicator would mean already entered numbers.

Morfa

Translation of: D
import morfa.base;
import morfa.functional.base;

template <TRange>
func rms(d: TRange): float
{
    var count = 1;
    return sqrt(reduce( (a: float, b: float) { count += 1; return a + b * b; }, d) / count);
}
 
func main(): void
{
    println(rms(1 .. 11));
}
Output:
6.204837

Nemerle

using System;
using System.Console;
using System.Math;

module RMS
{
    RMS(x : list[int]) : double
    {
        def sum = x.Map(fun (x) {x*x}).FoldLeft(0, _+_);
        Sqrt((sum :> double) / x.Length)
    }
    
    Main() : void
    {
        WriteLine("RMS of [1 .. 10]: {0:g6}", RMS($[1 .. 10]));
    }
}

NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg maxV .
if maxV = '' | maxV = '.' then maxV = 10

sum = 0
loop nr = 1 for maxV
  sum = sum + nr ** 2
  end nr
rmsD = Math.sqrt(sum / maxV)

say 'RMS of values from 1 to' maxV':' rmsD

return
Output:
RMS of values from 1 to 10: 6.204836822995428

Nim

from math import sqrt, sum
from sequtils import mapIt
 
proc qmean(num: seq[float]): float =
  result = num.mapIt(it * it).sum
  result = sqrt(result / float(num.len))
 
echo qmean(@[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0])
Output:
6.204836822995428

Oberon-2

Oxford Oberon-2

MODULE QM;
IMPORT ML := MathL, Out;
VAR
	nums: ARRAY 10 OF LONGREAL;
	i: INTEGER;
	
PROCEDURE Rms(a: ARRAY OF LONGREAL): LONGREAL;
VAR
	i: INTEGER;
	s: LONGREAL;
BEGIN
	s := 0.0;
	FOR i := 0 TO LEN(a) - 1 DO
		s := s + (a[i] * a[i])
	END;
	RETURN ML.Sqrt(s / LEN(a))
END Rms;
	
BEGIN
	FOR i := 0 TO LEN(nums) - 1 DO
		nums[i] := i + 1
	END;
	Out.String("Quadratic Mean: ");Out.LongReal(Rms(nums));Out.Ln
END QM.
Output:
Quadratic Mean: 6.20483682300

Objeck

bundle Default {
  class Hello {
    function : Main(args : String[]) ~ Nil {
      values := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
      RootSquareMean(values)->PrintLine();
    }
    
    function : native : RootSquareMean(values : Float[]) ~ Float {
      sum := 0.0;
      each(i : values) {
        x := values[i]->Power(2.0);
        sum += values[i]->Power(2.0);
      };
      
      return (sum / values->Size())->SquareRoot();
    }
  }
}

OCaml

let rms a =
  sqrt (Array.fold_left (fun s x -> s +. x*.x) 0.0 a /.
        float_of_int (Array.length a))
;;

rms (Array.init 10 (fun i -> float_of_int (i+1))) ;;
(* 6.2048368229954285 *)

Oforth

10 seq map(#sq) sum 10.0 / sqrt .
Output:
6.20483682299543

ooRexx

call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)

::routine testAverage
  use arg list
  say "list =" list~toString("l", ", ")
  say "root mean square =" rootmeansquare(list)
  say

::routine rootmeansquare
  use arg numbers
  -- return zero for an empty list
  if numbers~isempty then return 0

  sum = 0
  do number over numbers
      sum += number * number
  end
  return rxcalcsqrt(sum/numbers~items)

::requires rxmath LIBRARY
Output:
list = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
root mean square = 6.20483682

list = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11
root mean square = 5.06630766

list = 30, 10, 20, 30, 40, 50, -100, 4.7, -1100
root mean square = 369.146476

Oz

declare
  fun {Square X} X*X end

  fun {RMS Xs}
     {Sqrt
      {Int.toFloat {FoldL {Map Xs Square} Number.'+' 0}}
      /
      {Int.toFloat {Length Xs}}}
  end
in 
  {Show {RMS {List.number 1 10 1}}}
Output:
6.2048

PARI/GP

General RMS calculation:

RMS(v)={
  sqrt(sum(i=1,#v,v[i]^2)/#v)
};

RMS(vector(10,i,i))

Specific functions for the first n positive integers:

RMS_first(n)={
  sqrt((n+1)*(2*n+1)/6)
};

RMS_first(10)

Asymptotically this is n/sqrt(3).

Perl

use v5.10.0;
sub rms
{
        my $r = 0;
        $r += $_**2 for @_;
        sqrt( $r/@_ );
}

say rms(1..10);

Phix

function rms(sequence s)
atom sqsum = 0
    for i=1 to length(s) do
        sqsum += power(s[i],2)
    end for
    return sqrt(sqsum/length(s))
end function
 
?rms({1,2,3,4,5,6,7,8,9,10})
Output:
6.204836823

Alternative, same output
You could make this a one-liner, for no gain and making it harder to debug - an explicitly named intermediate such as sqsum adds no additional overhead compared to the un-named hidden temporary variable the compiler would otherwise use anyway, and of course sqsum can be examined/verified to pinpoint any error more effectively. The last (commented-out) line also removes the function call, but of course it has also removed every last descriptive hint of what it is supposed to be doing as well.

function rms(sequence s)
    atom sqsum = sum(apply(true,power,{s,2}))
    return sqrt(sqsum/length(s))
end function
?rms(tagset(10))
-- ?sqrt(sum(apply(true,power,{tagset(10),2}))/10) -- (ugh)

Phixmonti

def rms
    0 swap
    len for
        get 2 power rot + swap
    endfor
    len rot swap / sqrt
enddef

0 tolist
10 for
    0 put
endfor
 
rms print

PHP

<?php
// Created with PHP 7.0

function rms(array $numbers)
{
    $sum = 0;

    foreach ($numbers as $number) {
        $sum += $number**2;
    }

    return sqrt($sum / count($numbers));
}

echo rms(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Output:
6.2048368229954

Picat

Translation of: Prolog
Works with: Picat
rms(Xs) = Y =>
    Sum = sum_of_squares(Xs),
    N = length(Xs),
    Y = sqrt(Sum / N).

sum_of_squares(Xs) = Sum =>
    Sum = 0,
    foreach (X in Xs)
        Sum := Sum + X * X
    end.

main =>
    Y = rms(1..10),
    printf("The root-mean-square of 1..10 is %f\n", Y).
Output:
The root-mean-square of 1..10 is 6.204837

PicoLisp

(scl 5)

(let Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0)
   (prinl
      (format
         (sqrt
            (*/
               (sum '((N) (*/ N N 1.0)) Lst)
               1.0
               (length Lst) )
            T )
         *Scl ) ) )
Output:
6.20484

PL/I

 atest: Proc Options(main);
 declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10);
 declare (n,RMS) Dec Float(15);
 n = hbound(A,1);
 RMS = sqrt(sum(A**2)/n);
 put Skip Data(rms);
 End;
Output:
RMS= 6.20483682299543E+0000;

PostScript

/findrms{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq{}
{
x length{
/sum x i get 2 exp sum add def
/i i 1 add def
}repeat
/sum sum x length div sqrt def
}ifelse
sum ==
}def

[1 2 3 4 5 6 7 8 9 10] findrms
Output:
6.20483685
Library: initlib
[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt

Potion

rms = (series) :
   total = 0.0
   series each (x): total += x * x.
   total /= series length
   total sqrt
.

rms((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print


Powerbuilder

long ll_x, ll_y, ll_product
decimal ld_rms

ll_x = 1
ll_y = 10
DO WHILE ll_x <= ll_y
	ll_product += ll_x * ll_x
	ll_x ++
LOOP
ld_rms = Sqrt(ll_product / ll_y)

//ld_rms value is 6.20483682299542849

PowerShell

function get-rms([float[]]$nums){
   $sqsum=$nums | foreach-object { $_*$_} | measure-object -sum | select-object -expand Sum
   return [math]::sqrt($sqsum/$nums.count)
}

get-rms @(1..10)

Processing

void setup() {
  float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  print(rms(numbers));
}

float rms(float[] nums) {
  float mean = 0;
  for (float n : nums) {
    mean += sq(n);
  }
  mean = sqrt(mean / nums.length);
  return mean;
}
Output:
6.204837

Prolog

Works with: GNU Prolog
:- initialization(main).

rms(Xs, Y) :-
    sum_of_squares(Xs, 0, Sum),
    length(Xs, N),
    Y is sqrt(Sum / N).

sum_of_squares([], Sum, Sum).

sum_of_squares([X|Xs], A, Sum) :-
    A1 is A + X * X,
    sum_of_squares(Xs, A1, Sum).

main :-
    bagof(X, between(1, 10, X), Xs),
    rms(Xs, Y),
    format('The root-mean-square of 1..10 is ~f\n', [Y]).
Output:
The root-mean-square of 1..10 is 6.204837

PureBasic

NewList MyList()  ; To hold a unknown amount of numbers to calculate

If OpenConsole()
  Define.d result
  Define i, sum_of_squares
  
  ;Populate a random amounts of numbers to calculate
  For i=0 To (Random(45)+5) ; max elements is unknown to the program
    AddElement(MyList())
    MyList()=Random(15)  ; Put in a random number
  Next

  Print("Averages/Root mean square"+#CRLF$+"of : ")  

  ; Calculate square of each element, print each & add them together
  ForEach MyList()  
    Print(Str(MyList())+" ")             ; Present to our user
    sum_of_squares+MyList()*MyList()     ; Sum the squares, e.g
  Next

  ;Present the result
  result=Sqr(sum_of_squares/ListSize(MyList()))
  PrintN(#CRLF$+"= "+StrD(result))
  
  PrintN("Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Python

Works with: Python version 3
>>> from math import sqrt
>>> def qmean(num):
	return sqrt(sum(n*n for n in num)/len(num))

>>> qmean(range(1,11))
6.2048368229954285

Note that function range in Python includes the first limit of 1, excludes the second limit of 11, and has a default increment of 1.

The Python 2 version of this is nearly identical, except you must cast the sum to a float to get float division instead of integer division; or better, do a from __future__ import division, which works on Python 2.2+ as well as Python 3, and makes division work consistently like it does in Python 3.


Alternatively in terms of reduce:

from functools import (reduce)
from math import (sqrt)


# rootMeanSquare :: [Num] -> Float
def rootMeanSquare(xs):
    return sqrt(reduce(lambda a, x: a + x * x, xs, 0) / len(xs))


print(
    rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
)
Output:
6.2048368229954285

Qi

(define rms
  R -> (sqrt (/ (APPLY + (MAPCAR * R R)) (length R))))


Quackery

Using the Quackery big number rational arithmetic library bigrat.qky.

[ $ "bigrat.qky" loadfile ] now!

[ [] swap
  witheach
    [ unpack 2dup v*
      join nested join ] ] is squareall (   [ --> [   )

[ dup size n->v rot
  0 n->v rot
  witheach
    [ unpack v+ ]
  2swap v/ ]               is arithmean (   [ --> n/d )
 
[ dip
  [ squareall arithmean ]
  vsqrt drop ]             is rms       ( [ n --> n/d )
 
say "The RMS of the integers 1 to 10, to 80 decimal places with rounding." cr
say "(Checked on Wolfram Alpha. The final digit is correctly rounded up.)" cr cr
 
' [ [ 1 1 ] [ 2 1 ] [ 3 1 ] [ 4 1 ] [  5 1 ] 
    [ 6 1 ] [ 7 1 ] [ 8 1 ] [ 9 1 ] [ 10 1 ] ]
 
( ^^^ the integers 1 to 10 represented as a nest of nested rational numbers )
 
80 rms 
80 point$ echo$
Output:
The RMS of the integers 1 to 10, to 80 decimal places with rounding.
(Checked on Wolfram Alpha. The final digit is correctly rounded up.)

6.20483682299542829806662097772473784992796529536414069376132632095482141678247123

R

The following function works for any vector x:

RMS <- function(x, na.rm = F) sqrt(mean(x^2, na.rm = na.rm))

RMS(1:10)
# [1] 6.204837

RMS(c(NA, 1:10))
# [1] NA

RMS(c(NA, 1:10), na.rm = T)
# [1] 6.204837

Racket

#lang racket
(define (rms nums)
  (sqrt (/ (for/sum ([n nums]) (* n n)) (length nums))))

Raku

(formerly Perl 6)

sub rms(*@nums) { sqrt ([+] @nums X** 2) / @nums }

say rms 1..10;

Here's a slightly more concise version, albeit arguably less readable:

sub rms { sqrt @_ R/ [+] @_ X** 2 }

REXX

REXX has no built-in   sqrt   function, so a RYO version is included here.

This particular   sqrt   function was programmed for speed, as it has two critical components:

  •   the initial guess (for the square root)
  •   the number of (increasing) decimal digits used during the computations


The   sqrt   code was optimized to use the minimum amount of digits (precision) for each iteration of the
calculation as well as a reasonable attempt at providing a first-guess square root by essentially halving
the number using logarithmic (base ten) arithmetic.

/*REXX program computes and displays the  root mean square (RMS)  of a number sequence. */
parse arg nums digs show .                       /*obtain the optional arguments from CL*/
if nums==''  |  nums==","  then nums=10          /*Not specified?  Then use the default.*/
if digs==''  |  digs==","  then digs=50          /* "      "         "   "   "     "    */
if show==''  |  show==","  then show=10          /* "      "         "   "   "     "    */
numeric digits digs                              /*uses  DIGS  decimal digits for calc. */
$=0;                     do j=1  for nums        /*process each of the   N   integers.  */
                         $=$ + j**2              /*sum the   squares   of the integers. */
                         end   /*j*/
                                                 /* [↓]  displays  SHOW  decimal digits.*/
rms=format( sqrt($/nums), , show ) / 1           /*divide by N, then calculate the SQRT.*/
say 'root mean square for 1──►'nums  "is: "  rms /*display the  root mean square (RMS). */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x;  if x=0  then return 0;  d=digits();  numeric digits;  m.=9
       numeric form;  parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;  g=g *.5'e'_ % 2
       h=d+6;    do j=0  while h>9;       m.j=h;                h=h%2+1;        end  /*j*/
                 do k=j+5  to 0  by -1;   numeric digits m.k;   g=(g+x/g)*.5;   end  /*k*/
       return g

output   when using the default inputs:

root mean square for 1──►10 is:  6.204836823

Ring

nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
decimals(5)
see "Average = " + average(nums) + nl

func average number
     for i = 1 to len(number)
         sum = sum + pow(number[i],2)
     next
     x = sqrt(sum / len(number))
     return x

RPL

≪ LIST→ → n 
  ≪ 0 1 n START SWAP SQ + NEXT 
     n / √ 
≫ ≫ 'RMS' STO
{ 1 2 3 4 5 6 7 8 9 10 } RMS
Output:
1: 6.204836823
Works with: HP version 48G
≪ DUP ≪ SQ + ≫ STREAM SWAP SIZE / √
≫ 'RMS' STO

Ruby

class Array
  def quadratic_mean
    Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
  end
end

class Range
  def quadratic_mean
    self.to_a.quadratic_mean
  end
end

(1..10).quadratic_mean  # => 6.2048368229954285

and a non object-oriented solution:

def rms(seq)
  Math.sqrt(seq.sum{|x| x*x}.fdiv(seq.size) )
end
puts rms (1..10)   # => 6.2048368229954285

Run BASIC

valueList$   = "1 2 3 4 5 6 7 8 9 10"
while word$(valueList$,i +1) <> ""             ' grab values from list
  thisValue  = val(word$(valueList$,i +1))     ' turn values into numbers
  sumSquares = sumSquares + thisValue ^ 2      ' sum up the squares
  i = i +1                                     ' 
wend
print "List of Values:";valueList$;" containing ";i;" values"
print "Root Mean Square =";(sumSquares/i)^0.5
Output:

List of Values:1 2 3 4 5 6 7 8 9 10 containing 10 values Root Mean Square =6.20483682

Rust

fn root_mean_square(vec: Vec<i32>) -> f32 {
    let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
    return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
}

fn main() {
    let vec = (1..11).collect();
    println!("The root mean square is: {}", root_mean_square(vec));
}
Output:
The root mean square is: 6.204837

S-lang

Many of math operations in S-Lang are 'vectorized', that is, given an array, they apply themselves to each element. In this case, that means no array_map() function needed. Also, "range arrays" have a built-in syntax.

define rms(arr)
{
  return sqrt(sum(sqr(arr)) / length(arr));
}

print(rms([1:10]));

Sather

class MAIN is
  -- irrms stands for Integer Ranged RMS
  irrms(i, f:INT):FLT
    pre i <= f
  is
    sum ::= 0;
    loop
      sum := sum + i.upto!(f).pow(2);
    end;
    return (sum.flt / (f-i+1).flt).sqrt;
  end;

  main is
    #OUT + irrms(1, 10) + "\n";
  end; 
end;

S-BASIC

var n, sqsum, sqmean, rms = real
sqsum = 0
for n = 1 to 10 do
  sqsum = sqsum + (n * n)
next n
sqmean = sqsum / n
rms = sqr(sqmean)
print "RMS of numbers from 1 to 10 = ";rms

end
Output:
RMS of numbers from 1 to 10 =  6.20484

Scala

def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size)
println(rms(1 to 10))
Output:
6.2048368229954285

Scheme

(define (rms nums)
  (sqrt (/ (apply + (map * nums nums))
           (length nums))))

(rms '(1 2 3 4 5 6 7 8 9 10))
Output:
6.20483682299543

Seed7

$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";

const array float: numbers is [] (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);

const func float: rms (in array float: numbers) is func
  result
    var float: rms is 0.0;
  local
    var float: number is 0.0;
    var float: sum is 0.0;
  begin
    for number range numbers do
      sum +:= number ** 2;
    end for;
    rms := sqrt(sum / flt(length(numbers)));
  end func;

const proc: main is func
  begin
    writeln(rms(numbers) digits 7);
  end func;

Shen

Works with: shen-scheme version 0.17
(declare scm.sqrt [number --> number])

(tc +)

(define mean
  { (list number) --> number }
  Xs -> (/ (sum Xs) (length Xs)))

(define square
  { number --> number }
  X -> (* X X))

(define rms
  { (list number) --> number }
  Xs -> (scm.sqrt (mean (map (function square) Xs))))

(define iota-h
  { number --> number --> (list number) }
  X X -> [X]
  X Lim -> (cons X (iota-h (+ X 1) Lim)))

(define iota
  { number --> (list number) }
  Lim -> (iota-h 1 Lim))

(output "~A~%" (rms (iota 10)))

Sidef

func rms(a) {
    sqrt(a.map{.**2}.sum / a.len)
}

say rms(1..10)

Using hyper operators, we can write it as:

func rms(a) { a »**» 2 «+» / a.len -> sqrt }
Output:
6.20483682299542829806662097772473784992796529536

Smalltalk

(((1 to: 10) inject: 0 into: [ :s :n | n*n + s ]) / 10) sqrt.

SNOBOL4

Works with: Macro Spitbol
Works with: CSnobol

There is no built-in sqrt( ) function in Snobol4+.

        define('rms(a)i,ssq') :(rms_end)
rms     i = i + 1; ssq = ssq + (a<i> * a<i>) :s(rms)
        rms = sqrt(1.0 * ssq / prototype(a)) :(return)
rms_end

*       # Fill array, test and display
        str = '1 2 3 4 5 6 7 8 9 10'; a = array(10)
loop    i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
        output = str ' -> ' rms(a)
end
Output:
1 2 3 4 5 6 7 8 9 10 -> 6.20483682

SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "calcrms" )
       @( description, "Compute the Root mean square of the numbers 1..10." )
       @( description, "The root mean square is also known by its initial RMS (or rms), and as the" )
       @( description, "quadratic mean.  The RMS is calculated as the mean of the squares of the" )
       @( description, "numbers, square-rooted" )
       @( see_also, "http://rosettacode.org/wiki/Averages/Root_mean_square" )
       @( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure calcrms is
  type float_arr is array(1..10) of float;
  list : constant float_arr := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);
  total: float := 0.0;
  rms  : float;
begin
  for p in arrays.first(list)..arrays.last(list) loop
      total := @ + list(p)**2;
  end loop;
  rms := numerics.sqrt( total / float(arrays.length(list)));
  ?  rms;
end calcrms;

Standard ML

fun rms(v: real vector) = 
  let
    val v' = Vector.map (fn x => x*x) v
    val sum = Vector.foldl op+ 0.0 v'
  in
    Math.sqrt( sum/real(Vector.length(v')) )
  end;

rms(Vector.tabulate(10, fn n => real(n+1)));
Output:
val it = 6.204836823 : real

Stata

Compute the RMS of a variable and return the result in r(rms).

program rms, rclass
	syntax varname(numeric) [if] [in]
	tempvar x
	gen `x'=`varlist'^2 `if' `in'
	qui sum `x' `if' `in'
	return scalar rms=sqrt(r(mean))
end

Example

clear
set obs 20
gen x=rnormal()

rms x
di r(rms)
1.0394189

rms x if x>0
di r(rms)
.7423647

Swift

extension Collection where Element: FloatingPoint {
  @inlinable
  public func rms() -> Element {
    return (lazy.map({ $0 * $0 }).reduce(0, +) / Element(count)).squareRoot()
  }
}

print("RMS of 1...10: \((1...10).map(Double.init).rms())")
Output:
RMS of 1...10: 6.2048368229954285

Tcl

Works with: Tcl version 8.5
proc qmean list {
    set sum 0.0
    foreach value $list { set sum [expr {$sum + $value**2}] }
    return [expr { sqrt($sum / [llength $list]) }]
}

puts "RMS(1..10) = [qmean {1 2 3 4 5 6 7 8 9 10}]"
Output:
RMS(1..10) = 6.2048368229954285

Ursala

using the mean function among others from the flo library

#import nat
#import flo

#cast %e

rms = sqrt mean sqr* float* nrange(1,10)
Output:
6.204837e+00

Vala

Valac probably needs to have the flag "-X -lm" added to include the C Math library.

double rms(double[] list){
	double sum_squares = 0;
	double mean;
	
	foreach ( double number in list){
		sum_squares += (number * number);
	}
	
	mean = Math.sqrt(sum_squares / (double) list.length);
	
	return mean;
} // end rms

public static void main(){
	double[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	double mean = rms(list);
	
	stdout.printf("%s\n", mean.to_string());
}
Output:
6.2048368229954285

VBA

Using Excel VBA

Private Function root_mean_square(s() As Variant) As Double
    For i = 1 To UBound(s)
        s(i) = s(i) ^ 2
    Next i
    root_mean_square = Sqr(WorksheetFunction.sum(s) / UBound(s))
End Function
Public Sub pythagorean_means()
    Dim s() As Variant
    s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
    Debug.Print root_mean_square(s)
End Sub

Without using Excel worksheetfunction:

Function rms(iLow As Integer, iHigh As Integer)
    Dim i As Integer
    If iLow > iHigh Then
        i = iLow
        iLow = iHigh
        iHigh = i
    End If
    For i = iLow To iHigh
        rms = rms + i ^ 2
    Next i
    rms = Sqr(rms / (iHigh - iLow + 1))
End Function

Sub foo()
    Debug.Print rms(1, 10)
End Sub

Output:

 6.20483682299543 

V (Vlang)

import math
 
fn main() {
    n := 10
    mut sum := 0.0
    for x := 1.0; x <= n; x++ {
        sum += x * x
    }
    println(math.sqrt(sum / n))
}
Output:
6.2048368229954

Wortel

@let {
  ; using a composition and a fork (like you would do in J)
  rms1 ^(@sqrt @(@sum / #) *^@sq)

  ; using a function with a named argument
  rms2 &a @sqrt ~/ #a @sum !*^@sq a

  [[
    !rms1 @to 10
    !rms2 @to 10
  ]]
}
Output:
[6.2048368229954285 6.2048368229954285]

Wren

var rms = ((1..10).reduce(0) { |acc, i| acc + i*i }/10).sqrt
System.print(rms)
Output:
6.2048368229954

XLISP

(defun quadratic-mean (xs)
    (sqrt
        (/
            (apply +
                (mapcar (lambda (x) (expt x 2)) xs))
            (length xs))))

; define a RANGE function, for testing purposes

(defun range (x y)
    (if (< x y)
        (cons x (range (+ x 1) y))))

; test QUADRATIC-MEAN

(print (quadratic-mean (range 1 11)))
Output:
6.20483682299543

XPL0

code CrLf=9;
code real RlOut=48;
int  N;
real S;
[S:= 0.0;
for N:= 1 to 10 do S:= S + sq(float(N));
RlOut(0, sqrt(S/10.0));
CrLf(0);
]
Output:
    6.20484

Yacas

Sqrt(Add((1 .. 10)^2)/10)

The above will give the precise solution , to downgrade to 6.20483682299, surround the expression with 'N()'.

zkl

fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() }

The order in the reduce function is important as it coerces n*n to float.

zkl: rms([1..10].walk())  //-->rms(T(1,2,3,4,5,6,7,8,9,10))
6.20484