Averages/Root mean square
Compute the Root mean square of the numbers 1..10.
You are encouraged to solve this task according to the task description, using any language you may know.
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:
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
<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: (
- 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
- 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>
BASIC
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
.
<lang qbasic>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</lang>
See also: BBC BASIC, Liberty BASIC, PureBasic, Run BASIC
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>
- 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.
<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>
- 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 ;
}</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
<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)
- 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() {
const n = 10 sum := 0. for x := 1.; x <= n; x++ { sum += x * x } fmt.Println(math.Sqrt(sum / n))
}</lang>
- Output:
6.2048368229954285
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
,
<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>
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:
<lang julia>sqrt(sum(A.^2.) / length(A))</lang>
or the implicit allocation of a new array by A.^2.
can be avoided by using sum
as a higher-order function: <lang julia>sqrt(sum(x -> x*x, A) / length(A))</lang>
One can also use an explicit loop for near-C performance
<lang julia>
function rms(A)
s = 0.0 for a in A s += a*a end return sqrt(s / length(A))
end
</lang>
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): <lang julia>norm(A) / sqrt(length(A))</lang>
Lasso
<lang Lasso>define rms(a::array)::decimal => { return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size)) } define range(start::integer,end::integer)::array => { local(o = array) loop(-from=#start,-to=#end) => { #o->insert(loop_count) } return #o } rms(range(1,10))</lang>
- Output:
6.204837
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>
Logo
<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>
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
<lang MATLAB>function rms = quadraticMean(list)
rms = sqrt(mean(list.^2));
end</lang> Solution: <lang MATLAB>>> quadraticMean((1:10))
ans =
6.204836822995429</lang>
Maxima
<lang maxima>L: makelist(i, i, 1, 10)$
rms(L) := sqrt(lsum(x^2, x, L)/length(L))$
rms(L), numer; /* 6.204836822995429 */</lang>
МК-61/52
<lang>0 П0 П1 С/П x^2 ИП0 x^2 ИП1 * + ИП1 1 + П1 / КвКор П0 БП 03</lang>
Instruction: В/О С/П Number С/П Number ...
Each time you press the С/П on the indicator would mean already entered numbers.
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>
NetRexx
<lang 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 </lang> Output:
RMS of values from 1 to 10: 6.204836822995428
Oberon-2
Oxford Oberon-2 <lang oberon2> 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. </lang> Output:
Quadratic Mean: 6.20483682300
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>
ooRexx
<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(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
</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
<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
<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>
Racket
<lang Racket>
- lang racket
(define (rms nums)
(sqrt (/ (for/sum ([n nums]) (* n n)) (length nums))))
</lang>
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.
<lang rexx>/*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</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>
Run BASIC
<lang runbasic>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</lang>
Output: List of Values:1 2 3 4 5 6 7 8 9 10 containing 10 values Root Mean Square =6.20483682
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
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
<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
- import flo
- 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
XPL0
<lang 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); ]</lang> Output:
6.20484