Averages/Root mean square: Difference between revisions

From Rosetta Code
Content added Content deleted
(cf.)
(Added BBC BASIC)
Line 110: Line 110:
6.204837
6.204837
</pre>
</pre>

=={{header|BBC BASIC}}==
<lang BBC BASIC> *FLOAT 64
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>


=={{header|C}}==
=={{header|C}}==

Revision as of 09:41, 17 May 2011

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

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

BBC BASIC

<lang BBC BASIC> *FLOAT 64

     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 <stdlib.h>

  1. include <stdio.h>
  2. include <math.h>

double rms(double *v, int n) {

int i;
double sum = 0.0;
for(i = 0; i < n; i++)
 sum += pow(v[i], 2);
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 EXIT_SUCCESS;

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

Common Lisp

<lang lisp>(defun rms (x)

 (sqrt (/ (reduce #'+ (mapcar (lambda (xi) (expt xi 2)) x))
          (length x))))

(rms (loop for i from 1 upto 10 collect i))</lang>

D

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

real rms(Td)(Td d) {

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

}

void main() {

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

}</lang> Output:

6.2048368229954282979

E

Using the same generic mean function as used in Averages/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: <lang>6.2048368229954285</lang>

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>

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>import java.lang.Math;

public class RMS {

public static double rms(double[] nums)
{
 double ms = 0;
 for (int i = 0; i < nums.length; i += 1)
  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.printf("The RMS of the numbers from 1 to 10 is %f.\n", rms(nums));
}

}</lang>

Output: <lang>The RMS of the array is 6.204837.</lang>

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>

MATLAB

<lang MATLAB>function rms = quadraticMean(list)

   rms = sqrt(sum(list.^2)/numel(list));

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

Library: initlib

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

Powerbuilder

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

(Python 3.X) <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.

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 (lambda (x) (* x x)) nums))
          (length nums))))

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

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

  1. import nat
  2. import flo
  1. cast %e

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

6.204837e+00