Averages/Root mean square

From Rosetta Code
Jump to: navigation, search
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:

x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}.

Cf. Averages/Pythagorean means

Contents

[edit] 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

[edit] 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

[edit] APL

 rms←{((+/⍵*2)÷⍴⍵)*0.5}
x←⍳10
 
rms x
6.204836823

[edit] AutoHotkey

[edit] 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

[edit] Avoiding a loop

Using these equations:
\sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} See wp:List of mathematical series

for a < b : \sum_{i=a}^b i^2 = \sum_{i=1}^b i^2 - \sum_{i=1}^{a-1} i^2

We can show that:
\sum_{i=a}^b i^2 = \frac{b(b+1)(2b+1)-a(a-1)(2a-1)}{6}

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

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

[edit] 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

[edit] 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)

[edit] 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;
}

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

[edit] 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 ))/10.0 );
std::cout << "The quadratic mean of the numbers 1 .. 10 is " << meansquare << " !\n" ;
return 0 ;
}

Output:

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

[edit] Clojure

(use '[clojure.contrib.math :only (sqrt)])
 
(defn rms [xs]
(sqrt (/ (reduce + (map #(* % %) xs))
(count xs))))
 
(println (rms (range 1 11)))

Output:

6.2048368229954285

[edit] 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])

[edit] 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)))))

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

Output:

6.2048368229954282979

[edit] 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.

[edit] 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

[edit] 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

[edit] 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

[edit] 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

[edit] 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))
}
}

[edit] Factor

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

[edit] 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

[edit] Fortran

Assume x stored in array x.

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

[edit] 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

[edit] 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

[edit] Haskell

Given the mean function defiend in Averages/Pythagorean means:

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

[edit] 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

[edit] 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

[edit] Io

rms := method (figs, (figs map(** 2) reduce(+) / figs size) sqrt)
 
rms( Range 1 to(10) asList ) println

[edit] 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.

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

Output:

The RMS of the numbers from 1 to 10 is 6.2048368229954285

[edit] JavaScript

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

[edit] 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

[edit]

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

[edit] 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})

[edit] Mathematica

RootMeanSquare@Range[10]

The above will give the precise solution \sqrt{\frac{77}{2}}, to downgrade to 6.20484, use '10.' to imply asking for numeric solution, or append '//N' after the whole expression.

[edit] MATLAB

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

Solution:

>> quadraticMean((1:10))
 
ans =
 
6.204836822995429

[edit] Maxima

L: makelist(i, i, 1, 10)$
 
rms(L) := sqrt(lsum(x^2, x, L)/length(L))$
 
rms(L), numer; /* 6.204836822995429 */

[edit] МК-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.

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

[edit] 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

[edit] 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

[edit] 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();
}
}
}

[edit] 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 *)

[edit] 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
 

[edit] 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

[edit] 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).

[edit] Perl

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

[edit] Perl 6

sub rms(*@nums) { sqrt [+](@nums X** 2) / @nums }
 
say rms 1..10;

[edit] 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);

[edit] 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

[edit] 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

[edit] 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

[edit] 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)

[edit] 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

[edit] 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 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.

[edit] Qi

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

[edit] R

sqrt(sum((1:10)^2/10))

or generally, for x

x<-1:10
sqrt(sum((x)^2/length(x)))

[edit] Racket

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

[edit] REXX

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

This particular SQRT function was programmed for speed, as this SQRT function has two critical components:

  • the initial guess (for the square root)
  • the number of 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 logrithmic (base ten) arithmetic.

/*REXX program to compute the  root mean square  of a series of numbers.*/
 
parse arg n . /*get the argument (maybe). */
if n=='' then n=10 /*Not specified? Then assume 10.*/
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 /*j*/
rms=sqrt(sum/n) /*divide by N, then get SQRT. */
say 'root mean square for 1──►'n "is" rms /*show & tell.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────SQRT subroutine─────────────────────────*/
sqrt: procedure; parse arg x;if x=0 then return 0;d=digits();numeric digits 11
g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1
if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;numeric digits d;return g/1
 
.sqrtGuess: if x<0 then say 'negative number' x; numeric form; m.=11
p=d+d%4+2; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2

output

root mean square for 1──►10 is 6.2048368229954282980666209777247378499279652953641

[edit] 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

and a non object-oriented solution:

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

[edit] 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

[edit] 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;

[edit] Scala

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

[edit] 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

[edit] 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;

[edit] Smalltalk

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

[edit] 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

[edit] 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

[edit] 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

[edit] 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

[edit] 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
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox