Averages/Root mean square: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add J)
(added Ursala)
Line 57: Line 57:
<pre>
<pre>
RMS(1..10) = 6.2048368229954285
RMS(1..10) = 6.2048368229954285
</pre>


=={{header|Ursala}}==
using the <code>mean</code> function among others from the <code>flo</code> library
<lang Ursala>
#import nat
#import flo

#cast %e

rms = sqrt mean sqr* float* nrange(1,10)
</lang>
output:
<pre>
6.204837e+00
</pre>
</pre>

Revision as of 23:40, 22 February 2010

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:

C.f. Averages/Pythagorean means

Haskell

Given the mean function defiend in Averages/Pythagorean means:

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

J

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

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

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>

Python

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

>>> numbers = range(1,11) # 1..10 >>> qmean(numbers) 6.2048368229954285</lang>

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