Averages/Root mean square: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|AWK}}: compute RMS)
m (<lang> needs a language)
Line 9: Line 9:
Cf. [[Averages/Pythagorean means]]
Cf. [[Averages/Pythagorean means]]
=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Float_Text_IO; use Ada.Float_Text_IO;
<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 29: Line 28:
list := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);
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);
put( rms(list) , Exp=>0);
end calcrms;
end calcrms;</lang>
</lang>
Output:
Output:
<pre>
<pre>
6.20484
6.20484
</pre>
</pre>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Standard - no extensions to language used}}
{{works with|ALGOL 68|Standard - no extensions to language used}}

{{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)}}
<lang algol68># Define the rms PROCedure & ABS OPerators for LONG... REAL #
<lang algol68># Define the rms PROCedure & ABS OPerators for LONG... REAL #
Line 76: Line 73:


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


rms x
rms x
6.204836823
6.204836823</lang>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Line 186: Line 181:
}
}
}</lang>
}</lang>

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}}

<lang csharp>using System;
<lang csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;
Line 238: Line 230:


(println (rms (range 1 11)))</lang>
(println (rms (range 1 11)))</lang>

Output:
Output:
<pre>
<pre>
Line 274: Line 265:
</pre>
</pre>


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


Line 299: Line 290:


=={{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]]:

<lang e>def makeMean(base, include, finish) {
<lang e>def makeMean(base, include, finish) {
return def mean(numbers) {
return def mean(numbers) {
Line 324: Line 313:


rms([1,2,3,4,5,6,7,8,9,10]).</lang>
rms([1,2,3,4,5,6,7,8,9,10]).</lang>

Output:
Output:
<lang>6.2048368229954285</lang>
<pre>6.2048368229954285</pre>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
Line 343: Line 331:
constant s = {1,2,3,4,5,6,7,8,9,10}
constant s = {1,2,3,4,5,6,7,8,9,10}
? rms(s)</lang>
? rms(s)</lang>

Output:
Output:
<pre>6.204836823</pre>
<pre>6.204836823</pre>
Line 349: Line 336:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Uses a lambda expression and function piping.
Uses a lambda expression and function piping.
<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]</lang>
<lang Fsharp>
Answer (in F# Interactive window):
let RMS (x:float list) : float = List.map (fun y -> y**2.0) x |> List.average |> System.Math.Sqrt
<pre>val res : float = 6.204836823</pre>

let res = RMS [1.0..10.0]
</lang>

Answer (in F# Interactive window):<pre>val res : float = 6.204836823</pre>


=={{header|Fantom}}==
=={{header|Fantom}}==
<lang fantom>class Main

<lang fantom>
class Main
{
{
static Float averageRms (Float[] nums)
static Float averageRms (Float[] nums)
Line 376: Line 358:
echo ("RMS Average of $a is: " + averageRms(a))
echo ("RMS Average of $a is: " + averageRms(a))
}
}
}</lang>
}
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
Line 399: Line 380:
=={{header|Fortran}}==
=={{header|Fortran}}==
Assume <math> x </math> stored in array x.
Assume <math> x </math> stored in array x.

<lang Fortran>print *,sqrt( sum(x**2)/size(x) )</lang>
<lang Fortran>print *,sqrt( sum(x**2)/size(x) )</lang>

=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<lang go>package main
Line 426: Line 407:
: ((list.collect { it*it }.sum()) / list.size()) ** 0.5
: ((list.collect { it*it }.sum()) / list.size()) ** 0.5
}</lang>
}</lang>

Test:
Test:
<lang groovy>def list = 1..10
<lang groovy>def list = 1..10
Line 434: Line 414:
Q: ${Q}
Q: ${Q}
"""</lang>
"""</lang>

Output:
Output:
<pre>list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<pre>list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 441: Line 420:
=={{header|Haskell}}==
=={{header|Haskell}}==
Given the <code>mean</code> function defiend in [[Averages/Pythagorean means]]:
Given the <code>mean</code> function defiend in [[Averages/Pythagorean means]]:

<lang haskell>main = print $ mean 2 [1 .. 10]</lang>
<lang haskell>main = print $ mean 2 [1 .. 10]</lang>


Line 479: Line 457:
<lang j> rms 1 + i. 10
<lang j> rms 1 + i. 10
6.20484</lang>
6.20484</lang>


<code>*:</code> means [http://jsoftware.com/help/dictionary/d112.htm square]
<code>*:</code> means [http://jsoftware.com/help/dictionary/d112.htm square]


Line 488: Line 464:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class RMS{
<lang java>public class RMS {
public static double rms(double[] nums){
public static double rms(double[] nums){
double ms = 0;
double ms = 0;
for (int i = 0; i < nums.length; i++)
for (int i = 0; i < nums.length; i++)
ms += nums[i] * nums[i];
ms += nums[i] * nums[i];
ms /= nums.length;
ms /= nums.length;
return Math.sqrt(ms);
return Math.sqrt(ms);
}
}


public static void main(String[] args){
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};
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 " + rms(nums));
System.out.println("The RMS of the numbers from 1 to 10 is " + rms(nums));
}
}
}</lang>
}</lang>

Output:
Output:
<pre>The RMS of the numbers from 1 to 10 is 6.2048368229954285</pre>
<pre>The RMS of the numbers from 1 to 10 is 6.2048368229954285</pre>
Line 591: Line 566:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<lang objeck>bundle Default {
bundle Default {
class Hello {
class Hello {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 609: Line 583:
}
}
}
}
}</lang>
}
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==

<lang ocaml>let rms a =
<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 /.
Line 634: Line 606:
in
in
{Show {RMS {List.number 1 10 1}}}</lang>
{Show {RMS {List.number 1 10 1}}}</lang>

Output:
Output:
<pre>
<pre>
Line 655: Line 626:
RMS_first(10)</lang>
RMS_first(10)</lang>
Asymptotically this is n/sqrt(3).
Asymptotically this is n/sqrt(3).

=={{header|Pascal}}==
See [[Averages/Root_mean_square#Delphi | Delphi]]


=={{header|Perl}}==
=={{header|Perl}}==
Line 678: Line 646:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>declare A(10) fixed decimal static initial (1,2,3,4,5,6,7,8,9,10);
<lang PL/I>
declare A(10) fixed decimal static initial (1,2,3,4,5,6,7,8,9,10);
n = hbound(A,1);
n = hbound(A,1);
RMS = sqrt(sum(A**2)/n);
RMS = sqrt(sum(A**2)/n);</lang>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 701: Line 667:


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang>
<lang postscript>/findrms{
/findrms{
/x exch def
/x exch def
/sum 0 def
/sum 0 def
Line 717: Line 682:
}def
}def


[1 2 3 4 5 6 7 8 9 10] findrms
[1 2 3 4 5 6 7 8 9 10] findrms</lang>
</lang>
Output:
Output:
<lang>
<pre>
6.20483685
6.20483685
</lang>
</pre>

{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<lang postscript>[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt</lang>
[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt
</lang>


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


Line 744: Line 705:


=={{header|PowerShell}}==
=={{header|PowerShell}}==

<lang PowerShell>function get-rms([float[]]$nums){
<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
Line 783: Line 743:
=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3}}
{{works with|Python|3}}

<lang Python>>>> from math import sqrt
<lang Python>>>> from math import sqrt
>>> def qmean(num):
>>> def qmean(num):
Line 795: Line 754:


=={{header|Qi}}==
=={{header|Qi}}==
<lang qi>(define rms

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



=={{header|R}}==
=={{header|R}}==
<lang R>
<lang R>sqrt(sum((1:10)^2/10))</lang>
sqrt(sum((1:10)^2/10))
</lang>
or generally, for x
or generally, for x
<lang R>
<lang R>x<-1:10
sqrt(sum((x)^2/length(x)))</lang>
x<-1:10
sqrt(sum((x)^2/length(x)))
</lang>



=={{header|REXX}}==
=={{header|REXX}}==
REXX has no built-in SQRT, so a simple version is included here.
REXX has no built-in SQRT, so a simple version is included here.
<lang rexx>/*REXX program to compute root mean square. */
<lang rexx>
/*REXX program to compute root mean square. */


parse arg n . /*get the argument (maybe). */
parse arg n . /*get the argument (maybe). */
Line 849: Line 798:


numeric digits d /*restore the original precision.*/
numeric digits d /*restore the original precision.*/
return g/1 /*normalize to old precision. */
return g/1 /*normalize to old precision. */</lang>
</lang>
Output:
Output:
<pre>
<pre style="height:10ex;overflow:scroll">
root mean square for 1-->10 is 6.2048368229954282980666209777247378499279652953641
root mean square for 1-->10 is 6.2048368229954282980666209777247378499279652953641
</pre>
</pre>
Line 896: Line 844:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size)

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


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 908: Line 853:


(rms '(1 2 3 4 5 6 7 8 9 10))</lang>
(rms '(1 2 3 4 5 6 7 8 9 10))</lang>

Output:
Output:
<lang>6.20483682299543</lang>
<pre>6.20483682299543</pre>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 938: Line 882:


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


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==

{{works with|Macro Spitbol}}
{{works with|Macro Spitbol}}
{{works with|CSnobol}}
{{works with|CSnobol}}

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

<lang SNOBOL4> define('rms(a)i,ssq') :(rms_end)
<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)
Line 959: Line 898:
output = str ' -> ' rms(a)
output = str ' -> ' rms(a)
end</lang>
end</lang>

Output:
Output:
<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>
Line 979: Line 917:
=={{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
<lang Ursala>
<lang Ursala>#import nat
#import nat
#import flo
#import flo


#cast %e
#cast %e


rms = sqrt mean sqr* float* nrange(1,10)
rms = sqrt mean sqr* float* nrange(1,10)</lang>
</lang>
output:
output:
<pre>
<pre>
Line 994: Line 930:
=={{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.
<lang vala>
<lang vala>double rms(double[] list){
double rms(double[] list){
double sum_squares = 0;
double sum_squares = 0;
double mean;
double mean;
Line 1,013: Line 948:
stdout.printf("%s\n", mean.to_string());
stdout.printf("%s\n", mean.to_string());
}</lang>
}
</lang>

Output:
Output:
<pre>
<pre>

Revision as of 18:39, 11 February 2012

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

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

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

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

Cf. Averages/Pythagorean means

Ada

<lang 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;</lang> 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)

<lang algol68># 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: (

  1. 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))

)</lang> Output:

crude rms(one to ten): +6.20483682299543e  +0
rms(one to ten): +6.20483682299543e  +0

APL

<lang APL> rms←{((+/⍵*2)÷⍴⍵)*0.5}

x←⍳10
rms x

6.204836823</lang>

AutoHotkey

Using a loop

<lang autohotkey>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)

}</lang> Message box shows:

6.204837

Avoiding a loop

Using these equations:
See wp:List of mathematical series

for  :

We can show that:
<lang autohotkey>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))

}</lang> Message box shows:

6.204837

AWK

<lang awk>#!/usr/bin/awk -f

  1. 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);

}</lang>

BBC BASIC

<lang bbcbasic> 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)</lang>

C

<lang c>#include <stdio.h>

  1. 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;

}</lang>

C#

<lang csharp>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);
       }
   }

}</lang> An alternative method demonstrating the more functional style introduced by LINQ and lambda expressions in C# 3.

Works with: C# version 3

<lang csharp>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((double)x.Sum(n => n * n) / x.Count());
       }
   }

}</lang>

C++

<lang Cpp>#include <iostream>

  1. include <vector>
  2. include <cmath>
  3. 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 ))/10.0 );
 std::cout << "The quadratic mean of the numbers 1 .. 10 is " << meansquare << " !\n" ;
 return 0 ;

}</lang> Output:

The quadratic mean of the numbers 1 .. 10 is 6.20484 !

Clojure

<lang clojure>(use '[clojure.contrib.math :only (sqrt)])

(defn rms [xs]

 (sqrt (/ (reduce + (map #(* % %) xs))

(count xs))))

(println (rms (range 1 11)))</lang> Output:

6.2048368229954285

CoffeeScript

Translation of: JavaScript

<lang coffeescript> 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])</lang>

Common Lisp

<lang 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)))))</lang>

D

<lang d>import std.stdio, std.math, std.algorithm, std.range;

real rms(R)(R d) {

 return sqrt(reduce!((a, b) => a + b * b)(d) / cast(real)d.length);

}

void main() {

 writefln("%.19f", rms(iota(1, 11)));

}</lang> Output:

6.2048368229954282979

Delphi/Pascal

<lang Delphi>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.</lang>

E

Using the same generic mean function as used in pythagorean means: <lang e>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() })</lang>

<lang e>? RMS(1..10)

  1. value: 6.2048368229954285</lang>

Erlang

<lang 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]).</lang> Output:

6.2048368229954285

Euphoria

<lang 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)</lang> Output:

6.204836823

F#

Uses a lambda expression and function piping. <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]</lang> Answer (in F# Interactive window):

val res : float = 6.204836823

Fantom

<lang 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))
 }

}</lang>

Factor

<lang factor>: root-mean-square ( seq -- mean )

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

Forth

<lang 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</lang>

Fortran

Assume stored in array x. <lang Fortran>print *,sqrt( sum(x**2)/size(x) )</lang>

Go

<lang go>package main

import (

   "fmt"
   "math"

)

func main() {

   sum := 0.
   for n := 1.; n <= 10; n++ {
       sum += n*n
   }
   fmt.Println(math.Sqrt(sum/10))

}</lang>

Groovy

Solution: <lang groovy>def quadMean = { list ->

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

}</lang> Test: <lang groovy>def list = 1..10 def Q = quadMean(list) println """ list: ${list}

  Q: ${Q}

"""</lang> Output:

list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   Q: 6.2048368229954285

Haskell

Given the mean function defiend in Averages/Pythagorean means: <lang haskell>main = print $ mean 2 [1 .. 10]</lang>

HicEst

<lang HicEst>sum = 0 DO i = 1, 10

  sum = sum + i^2

ENDDO WRITE(ClipBoard) "RMS(1..10) = ", (sum/10)^0.5 </lang> RMS(1..10) = 6.204836823

Icon and Unicon

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


<lang Icon>procedure qmean(L[]) #: quadratic mean

  local m
  if *L = 0 then fail
  every (m := 0.0) +:= !L^2
  return sqrt(m / *L)

end</lang>

Io

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

rms( Range 1 to(10) asList ) println</lang>

J

Solution: <lang j>rms=: (+/ % #)&.:*:</lang>

Example Usage: <lang j> rms 1 + i. 10 6.20484</lang> *: 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

<lang java>public class RMS {

   public static double rms(double[] nums){
       double ms = 0;
       for (int i = 0; i < nums.length; i++)
           ms += nums[i] * nums[i];
       ms /= nums.length;
       return Math.sqrt(ms);
   }
   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 " + rms(nums));
   }

}</lang> Output:

The RMS of the numbers from 1 to 10 is 6.2048368229954285

JavaScript

Works with: JavaScript version 1.8

,

Works with: Firefox version 3.0

<lang javascript>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</lang>

Liberty BASIC

<lang lb>' [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</lang>

<lang logo>to rms :v

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

end

show rms iseq 1 10</lang>

Lua

<lang 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})</lang>

Mathematica

<lang Mathematica>RootMeanSquare@Range[10]</lang>

Nemerle

<lang 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]));
   }

}</lang>

MATLAB

<lang MATLAB>function rms = quadraticMean(list)

   rms = sqrt(mean(list.^2));

end</lang> Solution: <lang MATLAB>>> quadraticMean((1:10))

ans =

  6.204836822995429</lang>

Objeck

<lang 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();
   }
 }

}</lang>

OCaml

<lang 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 *)</lang>

Oz

<lang 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}}}</lang>

Output:

6.2048

PARI/GP

General RMS calculation: <lang parigp>RMS(v)={

 sqrt(sum(i=1,#v,v[i]^2)/#v)

};

RMS(vector(10,i,i))</lang>

Specific functions for the first n positive integers: <lang parigp>RMS_first(n)={

 sqrt((n+1)*(2*n+1)/6)

};

RMS_first(10)</lang> Asymptotically this is n/sqrt(3).

Perl

<lang perl>use v5.10.0; sub rms {

       my $r = 0;
       $r += $_**2 for @_;
       return sqrt( $r/@_ );

}

say rms(1..10);</lang>

Perl 6

<lang perl6>sub rms(*@nums) {

   sqrt( ([+] @nums X** 2) / +@nums );

}

say rms(1..10);</lang>

PL/I

<lang PL/I>declare A(10) fixed decimal static initial (1,2,3,4,5,6,7,8,9,10); n = hbound(A,1); RMS = sqrt(sum(A**2)/n);</lang>

PicoLisp

<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)

  (prinl
     (format
        (sqrt
           (*/
              (sum '((N) (*/ N N 1.0)) Lst)
              1.0
              (length Lst) )
           T )
        *Scl ) ) )</lang>

Output:

6.20484

PostScript

<lang 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</lang> Output:

6.20483685
Library: initlib

<lang postscript>[1 10] 1 range dup 0 {dup * +} fold exch length div sqrt</lang>

Powerbuilder

<lang 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</lang>

PowerShell

<lang 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) </lang>

PureBasic

<lang 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</lang>

Python

Works with: Python version 3

<lang Python>>>> from math import sqrt >>> def qmean(num): return sqrt(sum(n*n for n in num)/len(num))

>>> qmean(range(1,11)) 6.2048368229954285</lang> 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 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.

Qi

<lang qi>(define rms

 R -> (sqrt (/ (APPLY + (MAPCAR * R R)) (length R))))</lang>

R

<lang R>sqrt(sum((1:10)^2/10))</lang> or generally, for x <lang R>x<-1:10 sqrt(sum((x)^2/length(x)))</lang>

REXX

REXX has no built-in SQRT, so a simple version is included here. <lang rexx>/*REXX program to compute root mean square. */

parse arg n . /*get the argument (maybe). */ if n== then n=10 /*if not specified, assume ten. */

numeric digits 50 /*let's go a little overboard. */

sum=0 /*sum of numbers squared (so far)*/

 do j=1 for n                         /*step through   N   integers.   */
 sum=sum+j**2                         /*sum the squares of the integers*/
 end

rms=sqrt(sum/n) /*divide by N, then get SQRT. */ say 'root mean square for 1-->'n "is" rms /*show & tell.*/ exit


/*SQRT subroutine*/ sqrt: procedure; parse arg x if x=0 then return 0 /*handle special case of zero. */ d=digits() /*get the current precision. */ numeric digits digits()+2 /*ensure extra precision. */ g=x/4 /*try get a so-so 1st guesstimate*/ old=0 /*set OLD guess to zero. */

 do forever
 g=.5*(g+x/g)                         /*do the nitty-gritty calculation*/
 if g=old then leave                  /*if G is the same as old, quit. */
 old=g                                /*save OLD for next iteration.   */
 end                                  /*  .5*   is faster than    /2   */

numeric digits d /*restore the original precision.*/ return g/1 /*normalize to old precision. */</lang> Output:

root mean square for 1-->10 is 6.2048368229954282980666209777247378499279652953641

Ruby

<lang ruby>class Array

 def quadratic_mean
   Math.sqrt( self.inject(0) {|s, y| s += y*y}.to_f / self.length )
 end

end

class Range

 def quadratic_mean
   self.to_a.quadratic_mean
 end

end

(1..10).quadratic_mean # => 6.20483682299543</lang>

and a non object-oriented solution: <lang ruby>def rms(seq)

 Math.sqrt(seq.inject(0.0) {|sum, x| sum += x*x} / seq.length)

end puts rms (1..10).to_a # => 6.2048368229954285</lang>

Sather

<lang 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;</lang>

Scala

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

Scheme

<lang scheme>(define (rms nums)

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

(rms '(1 2 3 4 5 6 7 8 9 10))</lang> Output:

6.20483682299543

Seed7

<lang 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;</lang>

Smalltalk

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

SNOBOL4

Works with: Macro Spitbol
Works with: CSnobol

There is no built-in sqrt( ) function in Snobol4+. <lang SNOBOL4> define('rms(a)i,ssq') :(rms_end) rms i = i + 1; ssq = ssq + (a * a) :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 @p :s(loop)

       output = str ' -> ' rms(a)

end</lang> Output:

1 2 3 4 5 6 7 8 9 10 -> 6.20483682

Tcl

Works with: Tcl version 8.5

<lang tcl>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}]"</lang> Output:

RMS(1..10) = 6.2048368229954285

Ursala

using the mean function among others from the flo library <lang Ursala>#import nat

  1. import flo
  1. cast %e

rms = sqrt mean sqr* float* nrange(1,10)</lang> output:

6.204837e+00

Vala

Valac probably needs to have the flag "-X -lm" added to include the C Math library. <lang vala>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()); }</lang> Output:

6.2048368229954285