F qmean(num)
   R sqrt(sum(num.map(n -> n * n)) / Float(num.len))

print(qmean(1..10))


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

BYTE FUNC Equal(REAL POINTER a,b)
  BYTE ARRAY x,y

  x=a y=b
  IF x(0)=y(0) AND x(1)=y(1) AND x(2)=y(2) THEN
    RETURN (1)
  FI
RETURN (0)

PROC Sqrt(REAL POINTER a,b)
  REAL z,half

  IntToReal(0,z)
  ValR("0.5",half)

  IF Equal(a,z) THEN
    RealAssign(z,b)
  ELSE
    Power(a,half,b)
  FI
RETURN

PROC Main()
  BYTE i
  REAL x,x2,sum,tmp

  IntToReal(0,sum)
  FOR i=1 TO 10
  DO
    IntToReal(i,x)
    RealMult(x,x,x2)
    RealAdd(sum,x2,tmp)
    RealAssign(tmp,sum)
  OD
  IntToReal(10,x)
  RealDiv(sum,x,tmp)
  Sqrt(tmp,x)

  Put(125) PutE() ;clear screen
  Print("RMS of 1..10 is ")
  PrintRE(x)
RETURN


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;


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


BEGIN

DECIMAL FUNCTION SQRT(X);
DECIMAL X;
BEGIN
    DECIMAL R1, R2, TOL;
    TOL := .00001;   % reasonable for most purposes %
    IF X >= 1.0 THEN
       BEGIN
          R1 := X;
          R2 := 1.0;
       END
    ELSE
       BEGIN
          R1 := 1.0;
          R2 := X;
       END;
    WHILE (R1-R2) > TOL DO
        BEGIN
            R1 := (R1+R2) / 2.0;
            R2 := X / R1;
        END;
    SQRT := R1;
END;

COMMENT - MAIN PROGRAM BEGINS HERE;

DECIMAL N, SQSUM, SQMEAN;

SQSUM := 0.0;
FOR N := 1.0 STEP 1.0 UNTIL 10.0 DO
    SQSUM := SQSUM + (N * N);
SQMEAN := SQSUM / (N - 1.0);
WRITE("RMS OF WHOLE NUMBERS 1.0 THROUGH 10.0 =", SQRT(SQMEAN));

END


begin
    % computes the root-mean-square of an array of numbers with               %
    % the specified lower bound (lb) and upper bound (ub)                     %
    real procedure rms( real    array numbers ( * )
                      ; integer value lb
                      ; integer value ub
                      ) ;
        begin
            real sum;
            sum := 0;
            for i := lb until ub do sum := sum + ( numbers(i) * numbers(i) );
            sqrt( sum / ( ( ub - lb ) + 1 ) )
        end rms ;

    % test the rms procedure with the numbers 1 to 10                         %
    real array testNumbers( 1 :: 10 );
    for i := 1 until 10 do testNumbers(i) := i;
    r_format := "A"; r_w := 10; r_d := 4; % set fixed point output           %
    write( "rms of 1 .. 10: ", rms( testNumbers, 1, 10 ) );

end.


-- rootMeanSquare :: [Num] -> Real
on rootMeanSquare(xs)
    script
        on |λ|(a, x)
            a + x * x
        end |λ|
    end script

    (foldl(result, 0, xs) / (length of xs)) ^ (1 / 2)
end rootMeanSquare

-- TEST -----------------------------------------------------------------------
on run

    rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

    -- > 6.204836822995
end run

-- GENERIC FUNCTIONS ----------------------------------------------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


rootMeanSquare: function [arr]->
    sqrt (sum map arr 'i -> i^2) // size arr

print rootMeanSquare 1..10


#!/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);
}


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


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


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


#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 ) ) / static_cast<double>( numbers.size() ) );
  std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ;
  return 0 ;
}


(defn rms [xs]
  (Math/sqrt (/ (reduce + (map #(* % %) xs))
	   (count xs))))

(println (rms (range 1 11)))


IDENTIFICATION DIVISION.
PROGRAM-ID. QUADRATIC-MEAN-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01  QUADRATIC-MEAN-VARS.
    05 N               PIC 99        VALUE 0.
    05 N-SQUARED       PIC 999.
    05 RUNNING-TOTAL   PIC 999       VALUE 0.
    05 MEAN-OF-SQUARES PIC 99V9(16).
    05 QUADRATIC-MEAN  PIC 9V9(15).
PROCEDURE DIVISION.
CONTROL-PARAGRAPH.
    PERFORM MULTIPLICATION-PARAGRAPH 10 TIMES.
    DIVIDE  RUNNING-TOTAL BY 10 GIVING MEAN-OF-SQUARES.
    COMPUTE QUADRATIC-MEAN = FUNCTION SQRT(MEAN-OF-SQUARES).
    DISPLAY QUADRATIC-MEAN UPON CONSOLE.
    STOP RUN.
MULTIPLICATION-PARAGRAPH.
    ADD      1         TO N.
    MULTIPLY N         BY N GIVING N-SQUARED.
    ADD      N-SQUARED TO RUNNING-TOTAL.


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


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


def rms(seq)
  Math.sqrt(seq.sum { |x| x*x } / seq.size)
end

puts rms (1..10).to_a


import std.stdio, std.math, std.algorithm, std.range;

real rms(R)(R d) pure {
    return sqrt(d.reduce!((a, b) => a + b * b) / real(d.length));
}

void main() {
    writefln("%.19f", iota(1, 11).rms);
}


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.


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


import extensions;
import system'routines;
import system'math;

extension op
{
    get RootMeanSquare()
        = (self.selectBy:(x => x * x).summarize(Real.new()) / self.Length).sqrt();
}

public program()
{
    console.printLine(new Range(1, 10).RootMeanSquare)
}


defmodule RC do
  def root_mean_square(enum) do
    enum
    |> square
    |> mean
    |> :math.sqrt
  end

  defp mean(enum), do: Enum.sum(enum) / Enum.count(enum)

  defp square(enum), do: (for x <- enum, do: x * x)
end

IO.puts RC.root_mean_square(1..10)


(defun rms (nums)
  (sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums))
           (float (length nums)))))

(rms (number-sequence 1 10))


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


PROGRAM ROOT_MEAN_SQUARE
BEGIN
  N=10
  FOR I=1 TO N DO
     S=S+I*I
  END FOR
  X=SQR(S/N)
  PRINT("Root mean square is";X)
END PROGRAM


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)


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]


: root-mean-square ( seq -- mean )
    [ [ sq ] map-sum ] [ length ] bi / sqrt ;


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


: rms ( faddr len -- frms )
  dup >r 0e
  floats bounds do
    i [email protected] 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


' FB 1.05.0 Win64

Function QuadraticMean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  Dim As Double sum = 0.0
  For i As Integer = LBound(array) To UBound(array)
    sum += array(i) * array(i)
  Next
  Return Sqr(sum/length)
End Function

Dim vector(1 To 10) As Double
For i As Integer = 1 To 10
  vector(i) = i
Next

Print "Quadratic mean (or RMS) is :"; QuadraticMean(vector())
Print
Print "Press any key to quit the program"
Sleep


import "futlib/math"

fun main(as: [n]f64): f64 =
  f64.sqrt ((reduce (+) 0.0 (map (**2.0) as)) / f64(n))


1, 10 rep (i)
   i i | (v) ;
0
 1, 10 rep (i)
   i dup mult +
   ]
10 div
 sqrt
 print


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


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


sum = 0
DO i = 1, 10
   sum = sum + i^2
ENDDO
WRITE(ClipBoard) "RMS(1..10) = ", (sum/10)^0.5


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


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

rms( Range 1 to(10) asList ) println


public class RootMeanSquare {

    public static double rootMeanSquare(double... nums) {
        double sum = 0.0;
        for (double num : nums)
            sum += num * num;
        return Math.sqrt(sum / nums.length);
    }

    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 " + rootMeanSquare(nums));
    }
}


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


def rms: length as $length
  | if $length == 0 then null
    else map(. * .) | add | sqrt / $length
    end ;


// version 1.0.5-2

fun quadraticMean(vector: Array<Double>) : Double {
    val sum = vector.sumByDouble { it * it }
    return Math.sqrt(sum / vector.size)
}

fun main(args: Array<String>) {
    val vector = Array(10, { (it + 1).toDouble() })
    print("Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}")
}


define rms(a::staticarray)::decimal => {
	return math_sqrt((with n in #a sum #n*#n) / decimal(#a->size))
}
rms(generateSeries(1,10)->asStaticArray)


'   [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


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

show rms iseq 1 10


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


y := [ seq(1..10) ]:
RMS := proc( x )
    return sqrt( Statistics:-Mean( x ^~ 2 ) );
end proc:
RMS( y );


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


fn RMS arr =
(
	local sumSquared = 0
	for i in arr do sumSquared += i^2
	return (sqrt (sumSquared/arr.count as float))
)


(dup *) :sq
('sq map sum) :sum-sq
(('sum-sq 'size) => cleave / sqrt) :rms

(1 2 3 4 5 6 7 8 9 10) rms puts!


0	П0	П1	С/П	x^2	ИП0	x^2	ИП1	*
+	ИП1	1	+	П1	/	КвКор	П0	БП
03


import morfa.base;
import morfa.functional.base;

template <TRange>
func rms(d: TRange): float
{
    var count = 1;
    return sqrt(reduce( (a: float, b: float) { count += 1; return a + b * b; }, d) / count);
}

func main(): void
{
    println(rms(1 .. 11));
}


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


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


from math import sqrt, sum
from sequtils import mapIt

proc qmean(num: seq[float]): float =
  result = num.mapIt(it * it).sum
  result = sqrt(result / float(num.len))

echo qmean(@[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0])


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.


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


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


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


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


function rms(sequence s)
atom sqsum = 0
    for i=1 to length(s) do
        sqsum += power(s[i],2)
    end for
    return sqrt(sqsum/length(s))
end function

?rms({1,2,3,4,5,6,7,8,9,10})


def rms
    0 swap
    len for
        get 2 power rot + swap
    endfor
    len rot swap / sqrt
enddef

0 tolist
10 for
    0 put
endfor

rms print


<?php
// Created with PHP 7.0

function rms(array $numbers)
{
    $sum = 0;

    foreach ($numbers as $number) {
        $sum += $number**2;
    }

    return sqrt($sum / count($numbers));
}

echo rms(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));


rms(Xs) = Y =>
    Sum = sum_of_squares(Xs),
    N = length(Xs),
    Y = sqrt(Sum / N).

sum_of_squares(Xs) = Sum =>
    Sum = 0,
    foreach (X in Xs)
        Sum := Sum + X * X
    end.

main =>
    Y = rms(1..10),
    printf("The root-mean-square of 1..10 is %f\n", Y).


 atest: Proc Options(main);
 declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10);
 declare (n,RMS) Dec Float(15);
 n = hbound(A,1);
 RMS = sqrt(sum(A**2)/n);
 put Skip Data(rms);
 End;


/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


rms = (series) :
   total = 0.0
   series each (x): total += x * x.
   total /= series length
   total sqrt
.

rms((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print


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


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)


void setup() {
  float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  print(rms(numbers));
}

float rms(float[] nums) {
  float mean = 0;
  for (float n : nums) {
    mean += sq(n);
  }
  mean = sqrt(mean / nums.length);
  return mean;
}


:- initialization(main).

rms(Xs, Y) :-
    sum_of_squares(Xs, 0, Sum),
    length(Xs, N),
    Y is sqrt(Sum / N).

sum_of_squares([], Sum, Sum).

sum_of_squares([X|Xs], A, Sum) :-
    A1 is A + X * X,
    sum_of_squares(Xs, A1, Sum).

main :-
    bagof(X, between(1, 10, X), Xs),
    rms(Xs, Y),
    format('The root-mean-square of 1..10 is ~f\n', [Y]).


F amean(num)
   R sum(num)/Float(num.len)

F gmean(num)
   R product(num) ^ (1.0/num.len)

F hmean(num)
   return num.len / sum(num.map(n -> 1.0/n))

V numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(amean(numbers))
print(gmean(numbers))
print(hmean(numbers))


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


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

>>> qmean(range(1,11))
6.2048368229954285


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


[ $ "bigrat.qky" loadfile ] now!

[ [] swap
  witheach
    [ unpack 2dup v*
      join nested join ] ] is squareall (   [ --> [   )

[ dup size n->v rot
  0 n->v rot
  witheach
    [ unpack v+ ]
  2swap v/ ]               is arithmean (   [ --> n/d )

[ dip
  [ squareall arithmean ]
  vsqrt drop ]             is rms       ( [ n --> n/d )

say "The RMS of the integers 1 to 10, to 80 decimal places with rounding." cr
say "(Checked on Wolfram Alpha. The final digit is correctly rounded up.)" cr cr

' [ [ 1 1 ] [ 2 1 ] [ 3 1 ] [ 4 1 ] [  5 1 ]
    [ 6 1 ] [ 7 1 ] [ 8 1 ] [ 9 1 ] [ 10 1 ] ]

( ^^^ the integers 1 to 10 represented as a nest of nested rational numbers )

80 rms
80 point$ echo$


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC InverseI(INT a,result)
  REAL one,x

  IntToReal(1,one)
  IntToReal(a,x)
  RealDiv(one,x,result)
RETURN

PROC ArithmeticMean(INT ARRAY a INT count REAL POINTER result)
  INT i
  REAL x,sum,tmp

  IntToReal(0,sum)
  FOR i=0 TO count-1
  DO
    IntToReal(a(i),x)
    RealAdd(sum,x,tmp)
    RealAssign(tmp,sum)
  OD
  IntToReal(count,tmp)
  RealDiv(sum,tmp,result)
RETURN

PROC GeometricMean(INT ARRAY a INT count REAL POINTER result)
  INT i
  REAL x,prod,tmp

  IntToReal(1,prod)
  FOR i=0 TO count-1
  DO
    IntToReal(a(i),x)
    RealMult(prod,x,tmp)
    RealAssign(tmp,prod)
  OD
  InverseI(count,tmp)
  Power(prod,tmp,result)
RETURN

PROC HarmonicMean(INT ARRAY a INT count REAL POINTER result)
  INT i
  REAL x,sum,tmp

  IntToReal(0,sum)
  FOR i=0 TO count-1
  DO
    InverseI(a(i),x)
    RealAdd(sum,x,tmp)
    RealAssign(tmp,sum)
  OD
  IntToReal(count,tmp)
  RealDiv(tmp,sum,result)
RETURN

PROC Main()
  BYTE i
  INT ARRAY a=[1 2 3 4 5 6 7 8 9 10]
  REAL result

  Put(125) PutE() ;clear screen

  ArithmeticMean(a,10,result)
  Print("Arithmetic mean=") PrintRE(result)
  GeometricMean(a,10,result)
  Print(" Geometric mean=") PrintRE(result)
  HarmonicMean(a,10,result)
  Print("  Harmonic mean=") PrintRE(result)
RETURN


function arithmeticMean(v:Vector.<Number>):Number
{
	var sum:Number = 0;
	for(var i: uint = 0; i < v.length; i++)
		sum += v[i];
	return sum/v.length;
}
function geometricMean(v:Vector.<Number>):Number
{
	var product:Number = 1;
	for(var i: uint = 0; i < v.length; i++)
		product *= v[i];
	return Math.pow(product, 1/v.length);
}
function harmonicMean(v:Vector.<Number>):Number
{
	var sum:Number = 0;
	for(var i: uint = 0; i < v.length; i++)
		sum += 1/v[i];
	return v.length/sum;
}
var list:Vector.<Number> = Vector.<Number>([1,2,3,4,5,6,7,8,9,10]);
trace("Arithmetic: ", arithmeticMean(list));
trace("Geometric: ", geometricMean(list));
trace("Harmonic: ", harmonicMean(list));


package Pythagorean_Means is
   type Set is array (Positive range <>) of Float;
   function Arithmetic_Mean (Data : Set) return Float;
   function Geometric_Mean  (Data : Set) return Float;
   function Harmonic_Mean   (Data : Set) return Float;
end Pythagorean_Means;


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


sub rms(*@nums) { sqrt [+](@nums X** 2) / @nums }

say rms 1..10;


/*REXX program computes and displays the  root mean square (RMS)  of a number sequence. */
parse arg nums digs show .                       /*obtain the optional arguments from CL*/
if nums==''  |  nums==","  then nums=10          /*Not specified?  Then use the default.*/
if digs==''  |  digs==","  then digs=50          /* "      "         "   "   "     "    */
if show==''  |  show==","  then show=10          /* "      "         "   "   "     "    */
numeric digits digs                              /*uses  DIGS  decimal digits for calc. */
$=0;                     do j=1  for nums        /*process each of the   N   integers.  */
                         $=$ + j**2              /*sum the   squares   of the integers. */
                         end   /*j*/
                                                 /* [↓]  displays  SHOW  decimal digits.*/
rms=format( sqrt($/nums), , show ) / 1           /*divide by N, then calculate the SQRT.*/
say 'root mean square for 1──►'nums  "is: "  rms /*display the  root mean square (RMS). */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x;  if x=0  then return 0;  d=digits();  numeric digits;  m.=9
       numeric form;  parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;  g=g *.5'e'_ % 2
       h=d+6;    do j=0  while h>9;       m.j=h;                h=h%2+1;        end  /*j*/
                 do k=j+5  to 0  by -1;   numeric digits m.k;   g=(g+x/g)*.5;   end  /*k*/
       return g


main: (
  INT count:=0;
  LONG REAL f, sum:=0, prod:=1, resum:=0;

  FORMAT real = $g(0,4)$; # preferred real format #

  FILE fbuf; STRING sbuf; associate(fbuf,sbuf);

  BOOL opts := TRUE;

  FOR i TO argc DO
    IF opts THEN # skip args up to the - token #
      opts := argv(i) NE "-"
    ELSE
      rewind(fbuf); sbuf := argv(i); get(fbuf,f);
      count +:= 1;
      sum +:= f;
      prod *:= f;
      resum +:= 1/f
    FI
  OD;
  printf(($"c: "f(real)l"s: "f(real)l"p: "f(real)l"r: "f(real)l$,count,sum,prod,resum));
  printf(($"Arithmetic mean = "f(real)l$,sum/count));
  printf(($"Geometric mean = "f(real)l$,prod**(1/count)));
  printf(($"Harmonic mean = "f(real)l$,count/resum))
)


begin
    % returns the arithmetic mean of the elements of n from lo to hi %
    real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ;
    begin
        real sum;
        sum := 0;
        for i := lo until hi do sum := sum + n( i );
        sum / ( 1 + ( hi - lo ) )
    end arithmeticMean ;
    % returns the geometric mean of the elements of n from lo to hi %
    real procedure geometricMean ( real array n ( * ); integer value lo, hi ) ;
    begin
        real product;
        product := 1;
        for i := lo until hi do product := product * n( i );
        exp( ln( product ) / ( 1 + ( hi - lo ) ) )
    end geometricMean ;
    % returns the harminic mean of the elements of n from lo to hi %
    real procedure harmonicMean ( real array n ( * ); integer value lo, hi ) ;
    begin
        real sum;
        sum := 0;
        for i := lo until hi do sum := sum + ( 1 / n( i ) );
        ( 1 + ( hi - lo ) ) / sum
    end harmonicMean ;

    real array v ( 1 :: 10 );
    for i := 1 until 10 do v( i ) := i;

    r_w := 10; r_d := 5; r_format := "A"; s_w := 0; % set output format %

    write( "Arithmetic mean: ", arithmeticMean( v, 1, 10 ) );
    write( "Geometric  mean: ",  geometricMean( v, 1, 10 ) );
    write( "Harmonic   mean: ",   harmonicMean( v, 1, 10 ) )

end.


#include <hopper.h>

/* An example of definitions in pseudo-natural language, with synonimous.
   These definitions can be inside a definition file (xxxx.h) */
#define getasinglelistof(_X_)   {_X_},
#synon  getasinglelistof        getalistof
#define integerrandomnumbers    _V1000_=-1,rand array(_V1000_),mulby(10),ceil,
#define randomnumbers           _V1000_=-1,rand array(_V1000_)
#define rememberitin(_X_)       _X_=0,cpy(_X_)
#synon  rememberitin            rememberthisnumbersin
#define rememberas(_X_)         mov(_X_)
#define remember(_X_)           {_X_}
//#synon  remember            with   ---> this exist in HOPPER.H
#defn   nowconsiderthis(_X_)    #ATOM#CMPLX,print
#synon  nowconsiderthis         nowconsider,considerthis,consider,nowputtext,puttext,andprint
#define andprintwithanewline    {"\n"}print
#synon  andprintwithanewline    printwithanewline
//#defn   andprint(_X_)           #ATOM#CMPLX,print
#define putanewline             {"\n"}
#define withanewline            "\n"
#define andprintit              print
#synon  andprintit              printit,andprint
#define showit                  show
#define afterdoingit            emptystack?,not,do{ {"I cannot continue due to retentive data "},throw(1001) }
#synon  afterdoingit            secondly,finally
#define then                    emptystack?do{ {"I cannot continue because data is missing "},throw(1000) }
/* why "#context" and not "#define"?
   becose "#context" need a value in the stack for continue.
   Internally, "domeanit" tranform to "gosub(calculatearithmeticmean)",
   and "gosub" works only if it finds a data in the stack */
#context  calculatethegeometricmean
#synon    calculatethegeometricmean   calculategeometricmean,getgeometricmean
#context  calculatetheharmonicmean
#synon    calculatetheharmonicmean    calculateharmonicmean,getharmonicmean
#context  calculatearitmethicmean
#synon    calculatearitmethicmean     calculatesinglemean,calculatemean,domeanit

main:
  consider this ("Arithmetic Mean: ")
  get a list of '10,10' integer random numbers; remember this numbers in 'list of numbers';
  then, do mean it, and print with a new line.
  after doing it, consider ("Geometric Mean: "), remember 'list of numbers', calculate the geometric mean;
  then, put a new line, and print it.
  /*
       Okay. This can be a bit long, if we have to write the program;
       But what if we just had to talk, and the language interpreter takes care of the rest?
  */
  secondly, now consider ("Harmonic Mean: "), with 'list of numbers', get harmonic mean, and print with a new line.
  finally, put text ("Original Array:\n"), and print (list of numbers, with a new line)
exit(0)
.locals
calculate aritmethic mean:
  stats(MEAN)
back
calculate the geometric mean:
  stats(GEOMEAN)
back
calculatetheharmonicmean:
  stats(HARMEAN)
back


nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
decimals(5)
see "Average = " + average(nums) + nl

func average number
     for i = 1 to len(number)
         sum = sum + pow(number[i],2)
     next
     x = sqrt(sum / len(number))
     return x


class Array
  def quadratic_mean
    Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
  end
end

class Range
  def quadratic_mean
    self.to_a.quadratic_mean
  end
end

(1..10).quadratic_mean  # => 6.2048368229954285


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


fn root_mean_square(vec: Vec<i32>) -> f32 {
    let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
    return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
}

fn main() {
    let vec = (1..11).collect();
    println!("The root mean square is: {}", root_mean_square(vec));
}


define rms(arr)
{
  return sqrt(sum(sqr(arr)) / length(arr));
}

print(rms([1:10]));


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;


 arithmetic←{(+/⍵)÷⍴⍵}
 geometric←{(×/⍵)*÷⍴⍵}
 harmonic←{(⍴⍵)÷(+/÷⍵)}

 x←⍳10

 arithmetic x
5.5
 geometric x
4.528728688
 harmonic x
3.414171521


-- arithmetic_mean :: [Number] -> Number
on arithmetic_mean(xs)

    -- sum :: Number -> Number -> Number
    script sum
        on |λ|(accumulator, x)
            accumulator + x
        end |λ|
    end script

    foldl(sum, 0, xs) / (length of xs)
end arithmetic_mean

-- geometric_mean :: [Number] -> Number
on geometric_mean(xs)

    -- product :: Number -> Number -> Number
    script product
        on |λ|(accumulator, x)
            accumulator * x
        end |λ|
    end script

    foldl(product, 1, xs) ^ (1 / (length of xs))
end geometric_mean

-- harmonic_mean :: [Number] -> Number
on harmonic_mean(xs)

    -- addInverse :: Number -> Number -> Number
    script addInverse
        on |λ|(accumulator, x)
            accumulator + (1 / x)
        end |λ|
    end script

    (length of xs) / (foldl(addInverse, 0, xs))
end harmonic_mean

-- TEST -----------------------------------------------------------------------
on run
    set {A, G, H} to ap({arithmetic_mean, geometric_mean, harmonic_mean}, ¬
        {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})

    {values:{arithmetic:A, geometric:G, harmonic:H}, inequalities:¬
        {|A >= G|:A ≥ G}, |G >= H|:G ≥ H}
end run

-- GENERIC FUNCTIONS ----------------------------------------------------------

-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set {nf, nx} to {length of fs, length of xs}
    set acc to {}
    repeat with i from 1 to nf
        tell mReturn(item i of fs)
            repeat with j from 1 to nx
                set end of acc to |λ|(contents of (item j of xs))
            end repeat
        end tell
    end repeat
    return acc
end ap

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


var n, sqsum, sqmean, rms = real
sqsum = 0
for n = 1 to 10 do
  sqsum = sqsum + (n * n)
next n
sqmean = sqsum / n
rms = sqr(sqmean)
print "RMS of numbers from 1 to 10 = ";rms

end


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


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

(rms '(1 2 3 4 5 6 7 8 9 10))


$ 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;


(declare scm.sqrt [number --> number])

(tc +)

(define mean
  { (list number) --> number }
  Xs -> (/ (sum Xs) (length Xs)))

(define square
  { number --> number }
  X -> (* X X))

(define rms
  { (list number) --> number }
  Xs -> (scm.sqrt (mean (map (function square) Xs))))

(define iota-h
  { number --> number --> (list number) }
  X X -> [X]
  X Lim -> (cons X (iota-h (+ X 1) Lim)))

(define iota
  { number --> (list number) }
  Lim -> (iota-h 1 Lim))

(output "~A~%" (rms (iota 10)))


func rms(a) {
    sqrt(a.map{.**2}.sum / a.len)
}

say rms(1..10)


arithmeticMean: function [arr]->
    average arr

geometricMean: function [arr]->
    (product arr) ^ 1//size arr

harmonicMean: function [arr]->
    (size arr) // sum map arr 'i [1//i]

print arithmeticMean 1..10
print geometricMean 1..10
print harmonicMean 1..10


#!/usr/bin/awk -f
{
    x  = $1;   # value of 1st column
    A += x;
    G += log(x);
    H += 1/x;
    N++;
}

END {
   print "Arithmethic mean: ",A/N;
   print "Geometric mean  : ",exp(G/N);
   print "Harmonic mean   : ",N/H;
}


        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


fun rms(v: real vector) =
  let
    val v' = Vector.map (fn x => x*x) v
    val sum = Vector.foldl op+ 0.0 v'
  in
    Math.sqrt( sum/real(Vector.length(v')) )
  end;

rms(Vector.tabulate(10, fn n => real(n+1)));


program rms, rclass
	syntax varname(numeric) [if] [in]
	tempvar x
	gen `x'=`varlist'^2 `if' `in'
	qui sum `x' `if' `in'
	return scalar rms=sqrt(r(mean))
end


extension Collection where Element: FloatingPoint {
  @inlinable
  public func rms() -> Element {
    return (lazy.map({ $0 * $0 }).reduce(0, +) / Element(count)).squareRoot()
  }
}

print("RMS of 1...10: \((1...10).map(Double.init).rms())")


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


      DIM a(9)
      a() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
      PRINT "Arithmetic mean = " ; FNarithmeticmean(a())
      PRINT "Geometric mean =  " ; FNgeometricmean(a())
      PRINT "Harmonic mean =  " ; FNharmonicmean(a())
      END

      DEF FNarithmeticmean(a())
      = SUM(a()) / (DIM(a(),1)+1)

      DEF FNgeometricmean(a())
      LOCAL a, I%
      a = 1
      FOR I% = 0 TO DIM(a(),1)
        a *= a(I%)
      NEXT
      = a ^ (1/(DIM(a(),1)+1))

      DEF FNharmonicmean(a())
      LOCAL b()
      DIM b(DIM(a(),1))
      b() = 1/a()
      = (DIM(a(),1)+1) / SUM(b())


#include <stdio.h>
#include <stdlib.h> // atoi()
#include <math.h> // pow()

int main(int argc, char* argv[])
{
  int i, count=0;
  double f, sum=0.0, prod=1.0, resum=0.0;

  for (i=1; i<argc; ++i) {
    f = atof(argv[i]);
    count++;
    sum += f;
    prod *= f;
    resum += (1.0/f);
  }
  //printf(" c:%d\n s:%f\n p:%f\n r:%f\n",count,sum,prod,resum);
  printf("Arithmetic mean = %f\n",sum/count);
  printf("Geometric mean = %f\n",pow(prod,(1.0/count)));
  printf("Harmonic mean = %f\n",count/resum);

  return 0;
}


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace PythMean
{
    static class Program
    {
        static void Main(string[] args) {
            var nums = from n in Enumerable.Range(1, 10) select (double)n;

            var a = nums.Average();
            var g = nums.Gmean();
            var h = nums.Hmean();

            Console.WriteLine("Arithmetic mean {0}", a);
            Console.WriteLine("Geometric mean  {0}", g);
            Console.WriteLine("Harmonic mean   {0}", h);

            Debug.Assert(a >= g && g >= h);
        }

        // Geometric mean extension method.
        static double Gmean(this IEnumerable<double> n) {
            return Math.Pow(n.Aggregate((s, i) => s * i), 1.0 / n.Count());
        }

        // Harmonic mean extension method.
        static double Hmean(this IEnumerable<double> n) {
            return n.Count() / n.Sum(i => 1.0 / i);
        }
    }
}


#import nat
#import flo

#cast %e

rms = sqrt mean sqr* float* nrange(1,10)


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


Private Function root_mean_square(s() As Variant) As Double
    For i = 1 To UBound(s)
        s(i) = s(i) ^ 2
    Next i
    root_mean_square = Sqr(WorksheetFunction.sum(s) / UBound(s))
End Function
Public Sub pythagorean_means()
    Dim s() As Variant
    s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
    Debug.Print root_mean_square(s)
End Sub


import math

fn main() {
    n := 10
    mut sum := 0.0
    for x := 1.0; x <= n; x++ {
        sum += x * x
    }
    println(math.sqrt(sum / n))
}


@let {
  ; using a composition and a fork (like you would do in J)
  rms1 ^(@sqrt @(@sum / #) *^@sq)

  ; using a function with a named argument
  rms2 &a @sqrt ~/ #a @sum !*^@sq a

  [[
    !rms1 @to 10
    !rms2 @to 10
  ]]
}


#include <vector>
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>

double toInverse ( int i ) {
   return  1.0 / i  ;
}

int main( ) {
   std::vector<int> numbers ;
   for ( int i = 1 ; i < 11 ; i++ )
      numbers.push_back( i ) ;
   double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;
   double geometric_mean =
      pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ;
   std::vector<double> inverses ;
   inverses.resize( numbers.size( ) ) ;
   std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ;
   double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!
   std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean "
      << geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
   return 0 ;
}


(use '[clojure.contrib.math :only (expt)])

(defn a-mean [coll]
  (/ (apply + coll) (count coll)))

(defn g-mean [coll]
  (expt (apply * coll) (/ (count coll))))

(defn h-mean [coll]
  (/ (count coll) (apply + (map / coll))))

(let [numbers (range 1 11)
      a (a-mean numbers) g (g-mean numbers) h (h-mean numbers)]
  (println a ">=" g ">=" h)
  (>= a g h))


var rms = ((1..10).reduce(0) { |acc, i| acc + i*i }/10).sqrt
System.print(rms)


(defun quadratic-mean (xs)
    (sqrt
        (/
            (apply +
                (mapcar (lambda (x) (expt x 2)) xs))
            (length xs))))

; define a RANGE function, for testing purposes

(defun range (x y)
    (if (< x y)
        (cons x (range (+ x 1) y))))

; test QUADRATIC-MEAN

(print (quadratic-mean (range 1 11)))


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


fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() }


a = [ 1..10 ]
arithmetic_mean = (a) -> a.reduce(((s, x) -> s + x), 0) / a.length
geometic_mean = (a) -> Math.pow(a.reduce(((s, x) -> s * x), 1), (1 / a.length))
harmonic_mean = (a) -> a.length / a.reduce(((s, x) -> s + 1 / x), 0)

A = arithmetic_mean a
G = geometic_mean a
H = harmonic_mean a

console.log "A = ", A, " G = ", G, " H = ", H
console.log "A >= G : ", A >= G, " G >= H : ", G >= H


(defun generic-mean (nums reduce-op final-op)
  (funcall final-op (reduce reduce-op nums)))

(defun a-mean (nums)
  (generic-mean nums #'+ (lambda (x) (/ x (length nums)))))

(defun g-mean (nums)
  (generic-mean nums #'* (lambda (x) (expt x (/ 1 (length nums))))))

(defun h-mean (nums)
  (generic-mean nums
                (lambda (x y) (+ x
                                 (/ 1 y)))
                (lambda (x) (/ (length nums) x))))

(let ((numbers (loop for i from 1 to 10 collect i)))
  (let ((a-mean (a-mean numbers))
        (g-mean (g-mean numbers))
        (h-mean (h-mean numbers)))
    (assert (> a-mean g-mean h-mean))
    (format t "a-mean ~a~%" a-mean)
    (format t "g-mean ~a~%" g-mean)
    (format t "h-mean ~a~%" h-mean)))


import std.stdio, std.algorithm, std.range, std.functional;

auto aMean(T)(T data) pure nothrow @nogc {
    return data.sum / data.length;
}

auto gMean(T)(T data) pure /*@nogc*/ {
    return data.reduce!q{a * b} ^^ (1.0 / data.length);
}

auto hMean(T)(T data) pure /*@nogc*/ {
    return data.length / data.reduce!q{ 1.0 / a + b };
}

void main() {
    immutable m = [adjoin!(hMean, gMean, aMean)(iota(1.0L, 11.0L))[]];
    writefln("%(%.19f %)", m);
    assert(m.isSorted);
}


program AveragesPythagoreanMeans;

{$APPTYPE CONSOLE}

uses Types, Math;

function ArithmeticMean(aArray: TDoubleDynArray): Double;
var
  lValue: Double;
begin
  Result := 0;
  for lValue in aArray do
    Result := Result + lValue;
  if Result > 0 then
    Result := Result / Length(aArray);
end;

function GeometricMean(aArray: TDoubleDynArray): Double;
var
  lValue: Double;
begin
  Result := 1;
  for lValue in aArray do
    Result := Result * lValue;
  Result := Power(Result, 1 / Length(aArray));
end;

function HarmonicMean(aArray: TDoubleDynArray): Double;
var
  lValue: Double;
begin
  Result := 0;
  for lValue in aArray do
    Result := Result + 1 / lValue;
  Result := Length(aArray) / Result;
end;

var
  lSourceArray: TDoubleDynArray;
  AMean, GMean, HMean: Double;
begin
  lSourceArray := TDoubleDynArray.Create(1,2,3,4,5,6,7,8,9,10);
  AMean := ArithmeticMean(lSourceArray));
  GMean := GeometricMean(lSourceArray));
  HMean := HarmonicMean(lSourceArray));
  if (AMean >= GMean) and (GMean >= HMean) then
    Writeln(AMean, " ≥ ", GMean, " ≥ ", HMean)
  else
    writeln("Error!");
end.


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 A := makeMean(0, fn b,x { b+x   }, fn acc,n { acc / n      })
def G := makeMean(1, fn b,x { b*x   }, fn acc,n { acc ** (1/n) })
def H := makeMean(0, fn b,x { b+1/x }, fn acc,n { n / acc      })


(define (A xs) (// (for/sum ((x xs)) x) (length xs)))

(define (G xs) (expt (for/product ((x xs)) x) (// (length xs))))

(define (H xs) (// (length xs) (for/sum ((x xs)) (// x))))

(define xs (range 1 11))
(and (>= (A xs) (G xs)) (>= (G xs) (H xs)))
    → #t


defmodule Means do
  def arithmetic(list) do
    Enum.sum(list) / length(list)
  end
  def geometric(list) do
    :math.pow(Enum.reduce(list, &(*/2)), 1 / length(list))
  end
  def harmonic(list) do
    1 / arithmetic(Enum.map(list, &(1 / &1)))
  end
end

list = Enum.to_list(1..10)
IO.puts "Arithmetic mean: #{am = Means.arithmetic(list)}"
IO.puts "Geometric mean:  #{gm = Means.geometric(list)}"
IO.puts "Harmonic mean:   #{hm = Means.harmonic(list)}"
IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}"


%% Author: Abhay Jain <[email protected]>

-module(mean_calculator).
-export([find_mean/0]).

find_mean() ->
%% This is function calling. First argument is the the beginning number
%% and second argument is the initial value of sum for AM & HM and initial value of product for GM.
	arithmetic_mean(1, 0),
	geometric_mean(1, 1),
	harmonic_mean(1, 0).

%% Function to calculate Arithmetic Mean
arithmetic_mean(Number, Sum) when Number > 10 ->
	AM = Sum / 10,
	io:format("Arithmetic Mean ~p~n", [AM]);
arithmetic_mean(Number, Sum) ->
	NewSum = Sum + Number,
	arithmetic_mean(Number+1, NewSum).

%% Function to calculate Geometric Mean
geometric_mean(Number, Product) when Number > 10 ->
	GM = math:pow(Product, 0.1),
	io:format("Geometric Mean ~p~n", [GM]);
geometric_mean(Number, Product) ->
	NewProd = Product * Number,
	geometric_mean(Number+1, NewProd).

%% Function to calculate Harmonic Mean
harmonic_mean(Number, Sum) when Number > 10 ->
	HM = 10 / Sum,
	io:format("Harmonic Mean ~p~n", [HM]);
harmonic_mean(Number, Sum) ->
	NewSum = Sum + (1/Number),
	harmonic_mean(Number+1, NewSum).


PROGRAM MEANS

DIM A[9]

PROCEDURE ARITHMETIC_MEAN(A[]->M)
      LOCAL S,I%
      NEL%=UBOUND(A,1)
      S=0
      FOR I%=0 TO NEL% DO
        S+=A[I%]
      END FOR
      M=S/(NEL%+1)
END PROCEDURE

PROCEDURE GEOMETRIC_MEAN(A[]->M)
      LOCAL S,I%
      NEL%=UBOUND(A,1)
      S=1
      FOR I%=0 TO NEL% DO
        S*=A[I%]
      END FOR
      M=S^(1/(NEL%+1))
END PROCEDURE

PROCEDURE HARMONIC_MEAN(A[]->M)
      LOCAL S,I%
      NEL%=UBOUND(A,1)
      S=0
      FOR I%=0 TO NEL% DO
        S+=1/A[I%]
      END FOR
      M=(NEL%+1)/S
END PROCEDURE

BEGIN
      A[]=(1,2,3,4,5,6,7,8,9,10)
      ARITHMETIC_MEAN(A[]->M)
      PRINT("Arithmetic mean = ";M)
      GEOMETRIC_MEAN(A[]->M)
      PRINT("Geometric mean =  ";M)
      HARMONIC_MEAN(A[]->M)
      PRINT("Harmonic mean =  ";M)
END PROGRAM


function arithmetic_mean(sequence s)
    atom sum
    if length(s) = 0 then
        return 0
    else
        sum = 0
        for i = 1 to length(s) do
            sum += s[i]
        end for
        return sum/length(s)
    end if
end function

function geometric_mean(sequence s)
    atom p
    p = 1
    for i = 1 to length(s) do
        p *= s[i]
    end for
    return power(p,1/length(s))
end function

function harmonic_mean(sequence s)
    atom sum
    if length(s) = 0 then
        return 0
    else
        sum = 0
        for i = 1 to length(s) do
            sum += 1/s[i]
        end for
        return length(s) / sum
    end if
end function

function true_or_false(atom x)
    if x then
        return "true"
    else
        return "false"
    end if
end function

constant s = {1,2,3,4,5,6,7,8,9,10}
constant arithmetic = arithmetic_mean(s),
    geometric = geometric_mean(s),
    harmonic = harmonic_mean(s)
printf(1,"Arithmetic: %g\n", arithmetic)
printf(1,"Geometric: %g\n", geometric)
printf(1,"Harmonic: %g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n",
    {true_or_false(arithmetic>=geometric and geometric>=harmonic)})


let P = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]

let arithmeticMean (x : float list) =
    x |> List.sum
      |> (fun acc -> acc / float (List.length(x)))

let geometricMean (x: float list) =
    x |> List.reduce (*)
      |> (fun acc -> Math.Pow(acc, 1.0 / (float (List.length(x)))))

let harmonicMean (x: float list) =
    x |> List.map (fun a -> 1.0 / a)
      |> List.sum
      |> (fun acc -> float (List.length(x)) / acc)

printfn "Arithmetic Mean: %A" (arithmeticMean P)
printfn "Geometric Mean: %A" (geometricMean P)
printfn "Harmonic Mean: %A" (harmonicMean P)


: a-mean ( seq -- mean )
    [ sum ] [ length ] bi / ;

: g-mean ( seq -- mean )
    [ product ] [ length recip ] bi ^ ;

: h-mean ( seq -- mean )
    [ length ] [ [ recip ] map-sum ] bi / ;


class Main
{
  static Float arithmeticMean (Int[] nums)
  {
    if (nums.size == 0) return 0.0f
    sum := 0
    nums.each |n| { sum += n }
    return sum.toFloat / nums.size
  }

  static Float geometricMean (Int[] nums)
  {
    if (nums.size == 0) return 0.0f
    product := 1
    nums.each |n| { product *= n }
    return product.toFloat.pow(1f/nums.size)
  }

  static Float harmonicMean (Int[] nums)
  {
    if (nums.size == 0) return 0.0f
    reciprocals := 0f
    nums.each |n| { reciprocals += 1f / n }
    return nums.size.toFloat / reciprocals
  }

  public static Void main ()
  {
    items := (1..10).toList
    // display results
    echo (arithmeticMean (items))
    echo (geometricMean (items))
    echo (harmonicMean (items))
    // check given relation
    if ((arithmeticMean (items) >= geometricMean (items)) &&
        (geometricMean (items) >= harmonicMean (items)))
      echo ("relation holds")
    else
      echo ("relation failed")
  }
}


: famean ( faddr n -- f )
  0e
  tuck floats bounds do
    i [email protected] f+
  float +loop
  0 d>f f/ ;

: fgmean ( faddr n -- f )
  1e
  tuck floats bounds do
    i [email protected] f*
  float +loop
  0 d>f 1/f f** ;

: fhmean ( faddr n -- f )
  dup 0 d>f  0e
  floats bounds do
    i [email protected] 1/f f+
  float +loop
  f/ ;

create test 1e f, 2e f, 3e f, 4e f, 5e f, 6e f, 7e f, 8e f, 9e f, 10e f,
test 10 famean fdup f.
test 10 fgmean fdup fdup f.
test 10 fhmean fdup f.
( A G G H )
f>= . f>= .  \ -1 -1


program Mean

  real :: a(10) = (/ (i, i=1,10) /)
  real :: amean, gmean, hmean

  amean = sum(a) / size(a)
  gmean = product(a)**(1.0/size(a))
  hmean = size(a) / sum(1.0/a)

  if ((amean < gmean) .or. (gmean < hmean)) then
    print*, "Error!"
  else
    print*, amean, gmean, hmean
  end if

end program Mean


' FB 1.05.0 Win64

Function ArithmeticMean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  Dim As Double sum = 0.0
  For i As Integer = LBound(array) To UBound(array)
    sum += array(i)
  Next
  Return sum/length
End Function

Function GeometricMean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  Dim As Double product = 1.0
  For i As Integer = LBound(array) To UBound(array)
    product *= array(i)
  Next
  Return product ^ (1.0 / length)
End Function

Function HarmonicMean(array() As Double) As Double
  Dim length As Integer = Ubound(array) - Lbound(array) + 1
  Dim As Double sum = 0.0
  For i As Integer = LBound(array) To UBound(array)
    sum += 1.0 / array(i)
  Next
  Return length / sum
End Function

Dim vector(1 To 10) As Double
For i As Integer = 1 To 10
  vector(i) = i
Next

Print "Arithmetic mean is :"; ArithmeticMean(vector())
Print "Geometric mean is  :"; GeometricMean(vector())
Print "Harmonic mean is   :"; HarmonicMean(vector())
Print
Print "Press any key to quit the program"
Sleep


import lists.zip

def
  mean( s, 0 ) = product( s )^(1/s.length())
  mean( s, p ) = (1/s.length() sum( x^p | x <- s ))^(1/p)

def
  monotone( [_], _ ) = true
  monotone( a1:a2:as, p ) = p( a1, a2 ) and monotone( a2:as, p )

means = [mean( 1..10, m ) | m <- [1, 0, -1]]

for (m, l) <- zip( means, ['Arithmetic', 'Geometric', 'Harmonic'] )
  println( "$l: $m" + (if m is Rational then " or ${m.doubleValue()}" else '') )

println( monotone(means, (>=)) )


fun arithmetic_mean(as: [n]f64): f64 =
  reduce (+) 0.0 (map (/f64(n)) as)

fun geometric_mean(as: [n]f64): f64 =
  reduce (*) 1.0 (map (**(1.0/f64(n))) as)

fun harmonic_mean(as: [n]f64): f64 =
  f64(n) / reduce (+) 0.0 (map (1.0/) as)

fun main(as: [n]f64): (f64,f64,f64) =
  (arithmetic_mean as,
   geometric_mean as,
   harmonic_mean as)


# The first two work with rationals or with floats
# (but bear in mind that support of floating point is very poor in GAP)
mean := v -> Sum(v) / Length(v);
harmean := v -> Length(v) / Sum(v, Inverse);
geomean := v -> EXP_FLOAT(Sum(v, LOG_FLOAT) / Length(v));

mean([1 .. 10]);
# 11/2
harmean([1 .. 10]);
# 25200/7381

v := List([1..10], FLOAT_INT);;
mean(v);
# 5.5
harmean(v);
# 3.41417
geomean(v);
# 4.52873


package main

import (
    "fmt"
    "math"
)

func main() {
    sum, sumr, prod := 0., 0., 1.
    for n := 1.; n <= 10; n++ {
        sum += n
        sumr += 1 / n
        prod *= n
    }
    a, g, h := sum/10, math.Pow(prod, .1), 10/sumr
    fmt.Println("A:", a, "G:", g, "H:", h)
    fmt.Println("A >= G >= H:", a >= g && g >= h)
}


def arithMean = { list ->
    list == null \
        ? null \
        : list.empty \
            ? 0 \
            : list.sum() / list.size()
}

def geomMean = { list ->
    list == null \
        ? null \
        : list.empty \
            ? 1 \
            : list.inject(1) { prod, item -> prod*item } ** (1 / list.size())
}

def harmMean = { list ->
    list == null \
        ? null \
        : list.empty \
            ? 0 \
            : list.size() / list.collect { 1.0/it }.sum()
}


import Data.List (genericLength)
import Control.Monad (zipWithM_)

mean :: Double -> [Double] -> Double
mean 0 xs = product xs ** (1 / genericLength xs)
mean p xs = (1 / genericLength xs * sum (map (** p) xs)) ** (1/p)

main = do
  let ms = zipWith ((. flip mean [1..10]). (,)) "agh" [1, 0, -1]
  mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms
  putStrLn $ " a >= g >= h is " ++  show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))


AGH = ALIAS( A, G, H ) ! named vector elements
AGH = (0, 1, 0)
DO i = 1, 10
   A = A + i
   G = G * i
   H = H + 1/i
ENDDO
AGH = (A/10, G^0.1, 10/H)

WRITE(ClipBoard, Name) AGH, "Result = " // (A>=G) * (G>=H)


link numbers     # for a/g/h means

procedure main()
every put(x := [], 1 to 10)
writes("x := [ "); every writes(!x," "); write("]")

write("Arithmetic mean:", a := amean!x)
write("Geometric mean:",g := gmean!x)
write("Harmonic mean:", h := hmean!x)
write(" a >= g >= h is ", if a >= g >= h then "true" else "false")
end


100 PROGRAM "Averages.bas"
110 NUMERIC ARR(1 TO 10)
120 FOR I=LBOUND(ARR) TO UBOUND(ARR)
130   LET ARR(I)=I
140 NEXT
150 PRINT "Arithmetic mean =";ARITHM(ARR)
160 PRINT "Geometric mean  =";GEOMETRIC(ARR)
170 PRINT "Harmonic mean   =";HARMONIC(ARR)
180 DEF ARITHM(REF A)
190   LET T=0
200   FOR I=LBOUND(A) TO UBOUND(A)
210     LET T=T+A(I)
220   NEXT
230   LET ARITHM=T/SIZE(A)
240 END DEF
250 DEF GEOMETRIC(REF A)
260   LET T=1
270   FOR I=LBOUND(A) TO UBOUND(A)
280     LET T=T*A(I)
290   NEXT
300   LET GEOMETRIC=T^(1/SIZE(A))
310 END DEF
320 DEF HARMONIC(REF A)
330   LET T=0
340   FOR I=LBOUND(A) TO UBOUND(A)
350     LET T=T+(1/A(I))
360   NEXT
370   LET HARMONIC=SIZE(A)/T
380 END DEF


amean=: +/ % #
gmean=: # %: */
hmean=: amean&.:%


import java.util.Arrays;
import java.util.List;

public class PythagoreanMeans {
    public static double arithmeticMean(List<Double> numbers) {
        if (numbers.isEmpty()) return Double.NaN;
        double mean = 0.0;
        for (Double number : numbers) {
            mean += number;
        }
        return mean / numbers.size();
    }

    public static double geometricMean(List<Double> numbers) {
        if (numbers.isEmpty()) return Double.NaN;
        double mean = 1.0;
        for (Double number : numbers) {
            mean *= number;
        }
        return Math.pow(mean, 1.0 / numbers.size());
    }

    public static double harmonicMean(List<Double> numbers) {
        if (numbers.isEmpty() || numbers.contains(0.0)) return Double.NaN;
        double mean = 0.0;
        for (Double number : numbers) {
            mean += (1.0 / number);
        }
        return numbers.size() / mean;
    }

    public static void main(String[] args) {
        Double[] array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
        List<Double> list = Arrays.asList(array);
        double arithmetic = arithmeticMean(list);
        double geometric = geometricMean(list);
        double harmonic = harmonicMean(list);
        System.out.format("A = %f  G = %f  H = %f%n", arithmetic, geometric, harmonic);
        System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
    }
}


(function () {
    'use strict';

    // arithmetic_mean :: [Number] -> Number
    function arithmetic_mean(ns) {
        return (
            ns.reduce( // sum
                function (sum, n) {
                    return (sum + n);
                },
                0
            ) / ns.length
        );
    }

    // geometric_mean :: [Number] -> Number
    function geometric_mean(ns) {
        return Math.pow(
            ns.reduce( // product
                function (product, n) {
                    return (product * n);
                },
                1
            ),
            1 / ns.length
        );
    }

    // harmonic_mean :: [Number] -> Number
    function harmonic_mean(ns) {
        return (
            ns.length / ns.reduce( // sum of inverses
                function (invSum, n) {
                    return (invSum + (1 / n));
                },
                0
            )
        );
    }

    var values = [arithmetic_mean, geometric_mean, harmonic_mean]
        .map(function (f) {
            return f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        }),
        mean = {
            Arithmetic: values[0], // arithmetic
            Geometric: values[1], // geometric
            Harmonic: values[2] // harmonic
        }

    return JSON.stringify({
        values: mean,
        test: "is A >= G >= H ? " +
            (
                mean.Arithmetic >= mean.Geometric &&
                mean.Geometric >= mean.Harmonic ? "yes" : "no"
            )
    }, null, 2);

})();


def amean: add/length;

def logProduct: map(log) | add;

def gmean:  (logProduct / length) | exp;

def hmean: length / (map(1/.) | add);

# Tasks:
 [range(1;11) ] | [amean, gmean, hmean] as $ans
 | ( $ans[],
   "amean > gmean > hmean => \($ans[0] > $ans[1] and $ans[1] > $ans[2] )" )


amean(A) = sum(A)/length(A)

gmean(A) = prod(A)^(1/length(A))

hmean(A) = length(A)/sum(1./A)


import kotlin.math.round
import kotlin.math.pow

fun Collection<Double>.geometricMean() =
    if (isEmpty()) Double.NaN
    else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size)

fun Collection<Double>.harmonicMean() =
    if (isEmpty() || contains(0.0)) Double.NaN
    else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 }

fun Double.toFixed(len: Int = 6) =
    round(this * 10.0.pow(len)) / 10.0.pow(len)

fun main() {
    val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
    val a = list.average()  // arithmetic mean
    val g = list.geometricMean()
    val h = list.harmonicMean()
    println("A = $a  G = ${g.toFixed()}  H = ${h.toFixed()}")
    println("A >= G is ${a >= g}, G >= H is ${g >= h}")
    require(g in h..a)
}


define arithmetic_mean(a::staticarray)::decimal => {
	//sum of the list divided by its length
	return (with e in #a sum #e) / decimal(#a->size)
}
define geometric_mean(a::staticarray)::decimal => {
	// The geometric mean is the nth root of the product of the list
	local(prod = 1)
	with e in #a do => { #prod *= #e }
	return math_pow(#prod,1/decimal(#a->size))
}
define harmonic_mean(a::staticarray)::decimal => {
	// The harmonic mean is n divided by the sum of the reciprocal of each item in the list
	return decimal(#a->size)/(with e in #a sum 1/decimal(#e))
}

arithmetic_mean(generateSeries(1,10)->asStaticArray)
geometric_mean(generateSeries(1,10)->asStaticArray)
harmonic_mean(generateSeries(1,10)->asStaticArray)


for i = 1 to 10
    a = a + i
next
ArithmeticMean = a/10

b = 1
for i = 1 to 10
    b = b * i
next
GeometricMean = b ^ (1/10)

for i = 1 to 10
    c = c + (1/i)
next
HarmonicMean = 10/c

print "ArithmeticMean: ";ArithmeticMean
print "Geometric Mean: ";GeometricMean
print "Harmonic Mean: ";HarmonicMean

if (ArithmeticMean>=GeometricMean) and (GeometricMean>=HarmonicMean) then
print "True"
else
print "False"
end if


to compute_means :count
  local "sum
  make "sum     0
  local "product
  make "product 1
  local "reciprocal_sum
  make "reciprocal_sum  0

  repeat :count [
    make "sum sum :sum repcount
    make "product product :product repcount
    make "reciprocal_sum sum :reciprocal_sum (quotient repcount)
  ]

  output (sentence (quotient :sum :count) (power :product (quotient :count))
                   (quotient :count :reciprocal_sum))
end

make "means compute_means 10
print sentence [Arithmetic mean is] item 1 :means
print sentence [Geometric mean is] item 2 :means
print sentence [Harmonic mean is] item 3 :means
bye


function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end
function pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

--arithmetic
a = pymean(nums, function(n) return n end, function(n) return n end)
--geometric
g = pymean(nums, math.log, math.exp)
--harmonic
h = pymean(nums, function(n) return 1/n end, function(n) return 1/n end)
print(a, g, h)
assert(a >= g and g >= h)


Module CheckIt {
      sum=lambda -> {
              Read m as array
              if len(m)=0 then =0 : exit
              sum=Array(m, Dimension(m,0))
              If len(m)=1 then =sum : exit
              k=each(m,2,-1)
              While k {
                  sum+=Array(k)
            }
            =sum
      }
      mean=lambda sum (a as array) ->{
            =sum(a)/len(a)
      }
      prod=lambda -> {
              m=array
              if len(m)=0 then =0 : exit
              prod=Array(m, Dimension(m,0))
              If len(m)=1 then =prod : exit
              k=each(m,2,-1)
              While k {
                  prod*=Array(k)
            }
            =prod
      }
      geomean=lambda prod (a as array) -> {
            =prod(a)^(1/len(a))
      }
      harmomean=lambda (a as array) -> {
              if len(a)=0 then =0 : exit
              sum=1/Array(a, Dimension(a,0))
              If len(a)=1 then =1/sum : exit
              k=each(a,2,-1)
              While k {
                  sum+=1/Array(k)
            }
            =len(a)/sum
      }
      Print sum((1,2,3,4,5))=15
      Print prod((1,2,3,4,5))=120
      Print mean((1,2,3,4,5))==3
      \\ use == to apply rounding before comparison
      Print geomean((1,2,3,4,5))==2.60517108469735
      Print harmomean((1,2,3,4,5))==2.18978102189784
      Generator =lambda x=1 ->{=x : x++}
      dim a(10)<<Generator()
      Print mean(a())==5.5
      Print geomean(a())==4.52872868811677
      Print harmomean(a())==3.41417152147412
}
CheckIt


x := [ seq( 1 .. 10 ) ];
Means := proc( x )
    uses Statistics;
    return Mean( x ), GeometricMean( x ), HarmonicMean( x );
end proc:
Arithmeticmean, Geometricmean, Harmonicmean := Means( x );

is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean );


Print["{Arithmetic Mean, Geometric Mean, Harmonic Mean} = ",
 [email protected][{Mean, GeometricMean, HarmonicMean}[[email protected]]]]


function [A,G,H] = pythagoreanMeans(list)

    A = mean(list);
    G = geomean(list);
    H = harmmean(list);

end


MODULE PythagoreanMeans;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT power;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
    i,cnt : CARDINAL;
    mean : LONGREAL;
BEGIN
    mean := 0.0;
    cnt := 0;
    FOR i:=0 TO HIGH(numbers) DO
        mean := mean + numbers[i];
        INC(cnt);
    END;
    RETURN mean / LFLOAT(cnt)
END ArithmeticMean;

PROCEDURE GeometricMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
    i,cnt : CARDINAL;
    mean : LONGREAL;
BEGIN
    mean := 1.0;
    cnt := 0;
    FOR i:=0 TO HIGH(numbers) DO
        mean := mean * numbers[i];
        INC(cnt);
    END;
    RETURN power(mean, 1.0 / LFLOAT(cnt))
END GeometricMean;

PROCEDURE HarmonicMean(numbers : ARRAY OF LONGREAL) : LONGREAL;
VAR
    i,cnt : CARDINAL;
    mean : LONGREAL;
BEGIN
    mean := 0.0;
    cnt := 0;
    FOR i:=0 TO HIGH(numbers) DO
        mean := mean + ( 1.0 / numbers[i]);
        INC(cnt);
    END;
    RETURN LFLOAT(cnt) / mean
END HarmonicMean;

CONST Size = 10;
TYPE DA = ARRAY[1..Size] OF LONGREAL;

VAR
    buf : ARRAY[0..63] OF CHAR;
    array : DA;
    arithmetic,geometric,harmonic : LONGREAL;
BEGIN
    array := DA{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};

    arithmetic := ArithmeticMean(array);
    geometric := GeometricMean(array);
    harmonic := HarmonicMean(array);

    WriteString("A = ");
    RealToStr(arithmetic, buf);
    WriteString(buf);
    WriteString(" G = ");
    RealToStr(geometric, buf);
    WriteString(buf);
    WriteString(" H = ");
    RealToStr(harmonic, buf);
    WriteString(buf);
    WriteLn;

    FormatString("A >= G is %b, G >= H is %b\n", buf, arithmetic >= geometric, geometric >= harmonic);
    WriteString(buf);

    ReadChar
END PythagoreanMeans.


Pyth(n)	New a,ii,g,h,x
	For ii=1:1:n set x(ii)=ii
	;
	; Average
	Set a=0 For ii=1:1:n Set a=a+x(ii)
	Set a=a/n
	;
	; Geometric
	Set g=1 For ii=1:1:n Set g=g*x(ii)
	Set g=g**(1/n)
	;
	; Harmonic
	Set h=0 For ii=1:1:n Set h=1/x(ii)+h
	Set h=n/h
	;
	Write !,"Pythagorean means for 1..",n,":",!
	Write "Average = ",a," >= Geometric ",g," >= harmonic ",h,!
	Quit
Do Pyth(10)

Pythagorean means for 1..10:
Average = 5.5 >= Geometric 4.528728688116178495 >= harmonic 3.414171521474055006


/* NetRexx */
options replace format comments java crossref symbols nobinary

numeric digits 20

a1 = ArrayList(Arrays.asList([Rexx 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]))
say "Arithmetic =" arithmeticMean(a1)", Geometric =" geometricMean(a1)", Harmonic =" harmonicMean(a1)

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arithmeticMean(numbers = java.util.List) public static returns Rexx
  -- somewhat arbitrary return for ooRexx
  if numbers.isEmpty then return "NaN"

  mean = 0
  number = Rexx
  loop number over numbers
      mean = mean + number
  end
  return mean / numbers.size

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method geometricMean(numbers = java.util.List) public static returns Rexx
  -- somewhat arbitrary return for ooRexx
  if numbers.isEmpty then return "NaN"

  mean = 1
  number = Rexx
  loop number over numbers
      mean = mean * number
  end
  return Math.pow(mean, 1 / numbers.size)

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method harmonicMean(numbers = java.util.List) public static returns Rexx
  -- somewhat arbitrary return for ooRexx
  if numbers.isEmpty then return "NaN"

  mean = 0
  number = Rexx
  loop number over numbers
      if number = 0 then return "Nan"
      mean = mean + (1 / number)
  end

  -- problem here...
  return numbers.size / mean


import math, sequtils, sugar

proc amean(num: seq[float]): float =
  sum(num) / float(len(num))

proc gmean(num: seq[float]): float =
  result = 1
  for n in num: result *= n
  result = pow(result, 1.0 / float(num.len))

proc hmean(num: seq[float]): float =
  for n in num: result += 1.0 / n
  result = float(num.len) / result

proc ameanFunctional(num: seq[float]): float =
  sum(num) / float(num.len)

proc gmeanFunctional(num: seq[float]): float =
  num.foldl(a * b).pow(1.0 / float(num.len))

proc hmeanFunctional(num: seq[float]): float =
  float(num.len) / sum(num.mapIt(1.0 / it))

let numbers = toSeq(1..10).map((x: int) => float(x))
echo amean(numbers), " ", gmean(numbers), " ", hmean(numbers)


MODULE PythMean;
IMPORT Out, ML := MathL;

PROCEDURE Triplets(a: ARRAY OF INTEGER;VAR triplet: ARRAY OF LONGREAL);
VAR
	i: INTEGER;
BEGIN
	triplet[0] := 0.0;triplet[1] := 0.0; triplet[2] := 0.0;
	FOR i:= 0 TO LEN(a) - 1 DO
		triplet[0] := triplet[0] + a[i];
		triplet[1] := triplet[1] + ML.Ln(a[i]);
		triplet[2] := triplet[2] + (1 / a[i])
	END
END Triplets;

PROCEDURE Means*(a: ARRAY OF INTEGER);
VAR
	triplet: ARRAY 3 OF LONGREAL;
BEGIN
	Triplets(a,triplet);
	Out.String("A(1 .. 10): ");Out.LongReal(triplet[0] / LEN(a));Out.Ln;
	Out.String("G(1 .. 10): ");Out.LongReal(ML.Exp(triplet[1]/ LEN(a)));Out.Ln;
	Out.String("H(1 .. 10): ");Out.LongReal(LEN(a) / triplet[2]);Out.Ln;
END Means;

VAR
	nums: ARRAY 10 OF INTEGER;
	i: INTEGER;
BEGIN
	FOR i := 0 TO LEN(nums) - 1 DO
		nums[i] := i + 1
	END;
	Means(nums)
END PythMean.


class PythagMeans {
  function : Main(args : String[]) ~ Nil {
    array := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
    arithmetic := ArithmeticMean(array);
    geometric := GeometricMean(array);
    harmonic := HarmonicMean(array);

    arith_geo := arithmetic >= geometric;
    geo_harm := geometric >= harmonic;

    "A = {$arithmetic}, G = {$geometric}, H = {$harmonic}"->PrintLine();
    "A >= G is {$arith_geo}, G >= H is {$geo_harm}"->PrintLine();
  }

  function : native : ArithmeticMean(numbers : Float[]) ~ Float {
    if(numbers->Size() = 0) { return -1.0; };

    mean := 0.0;
    each(i : numbers) {
      mean += numbers[i];
    };

    return mean / numbers->Size();
  }

  function : native : GeometricMean(numbers : Float[]) ~ Float {
    if(numbers->Size() = 0) { return -1.0; };

    mean := 1.0;
    each(i : numbers) {
      mean *= numbers[i];
    };

    return mean->Power(1.0 / numbers->Size());
  }

  function : native : HarmonicMean(numbers : Float[]) ~ Float {
    if(numbers->Size() = 0) { return -1.0; };

    mean := 0.0;
    each(i : numbers) {
      mean += (1.0 / numbers[i]);
    };

    return numbers->Size() / mean;
  }
}


let means v =
  let n = Array.length v
  and a = ref 0.0
  and b = ref 1.0
  and c = ref 0.0 in
  for i=0 to n-1 do
    a := !a +. v.(i);
    b := !b *. v.(i);
    c := !c +. 1.0/.v.(i);
  done;
  let nn = float_of_int n in
  (!a /. nn, !b ** (1.0/.nn), nn /. !c)
;;


    A = mean(list);     % arithmetic mean
    G = mean(list,'g'); % geometric mean
    H = mean(list,'a'); % harmonic mean


import: mapping

: A ( x )
   x sum
   x size dup ifZero: [ 2drop null ] else: [ >float / ]
;

: G( x )   #* x reduce  x size inv powf ;

: H( x )   x size x map( #inv ) sum / ;

: averages
| g |
   "Geometric mean  :" . 10 seq G dup .cr ->g
   "Arithmetic mean :" . 10 seq A dup . g >= ifTrue: [ " ==> A >= G" .cr ]
   "Harmonic mean   :" . 10 seq H dup . g <= ifTrue: [ " ==> G >= H" .cr ]
;


a = .array~of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a)

::routine arithmeticMean
  use arg numbers
  -- somewhat arbitrary return for ooRexx
  if numbers~isEmpty then return "NaN"

  mean = 0
  loop number over numbers
      mean += number
  end
  return mean / numbers~items

::routine geometricMean
  use arg numbers
  -- somewhat arbitrary return for ooRexx
  if numbers~isEmpty then return "NaN"

  mean = 1
  loop number over numbers
      mean *= number
  end

  return rxcalcPower(mean, 1 / numbers~items)

::routine harmonicMean
  use arg numbers
  -- somewhat arbitrary return for ooRexx
  if numbers~isEmpty then return "NaN"

  mean = 0
  loop number over numbers
      if number = 0 then return "Nan"
      mean += 1 / number
  end

  -- problem here....
  return numbers~items / mean

::requires rxmath LIBRARY


declare
  %% helpers
  fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end
  fun {Product Xs} {FoldL Xs Number.'*' 1.0} end
  fun {Len Xs} {Int.toFloat {Length Xs}} end

  fun {AMean Xs}
     {Sum Xs}
     /
     {Len Xs}
  end

  fun {GMean Xs}
     {Pow
      {Product Xs}
      1.0/{Len Xs}}
  end

  fun {HMean Xs}
     {Len Xs}
     /
     {Sum {Map Xs fun {$ X} 1.0 / X end}}
  end

  Numbers = {Map {List.number 1 10 1} Int.toFloat}

  [A G H] = [{AMean Numbers} {GMean Numbers} {HMean Numbers}]
in
  {Show [A G H]}
  A >= G = true
  G >= H = true


arithmetic(v)={
  sum(i=1,#v,v[i])/#v
};
geometric(v)={
  prod(i=1,#v,v[i])^(1/#v)
};
harmonic(v)={
  #v/sum(i=1,#v,1/v[i])
};

v=vector(10,i,i);
[arithmetic(v),geometric(v),harmonic(v)]


sub A
{
        my $a = 0;
        $a += $_ for @_;
        return $a / @_;
}
sub G
{
        my $p = 1;
        $p *= $_ for @_;
        return  $p**(1/@_); # power of 1/n == root of n
}
sub H
{
        my $h = 0;
        $h += 1/$_ for @_;
        return @_/$h;
}
my @ints = (1..10);

my $a = A(@ints);
my $g = G(@ints);
my $h = H(@ints);

print "A=$a\nG=$g\nH=$h\n";
die "Error" unless $a >= $g and $g >= $h;


with javascript_semantics
function arithmetic_mean(sequence s)
    return sum(s)/length(s)
end function

function geometric_mean(sequence s)
    return power(product(s),1/length(s))
end function

function harmonic_mean(sequence s)
    return length(s)/sum(sq_div(1,s))
end function

constant s = {1,2,3,4,5,6,7,8,9,10}
constant arithmetic = arithmetic_mean(s),
         geometric = geometric_mean(s),
         harmonic = harmonic_mean(s)
printf(1,"Arithmetic: %.10g\n", arithmetic)
printf(1,"Geometric: %.10g\n", geometric)
printf(1,"Harmonic: %.10g\n", harmonic)
printf(1,"Arithmetic>=Geometric>=Harmonic: %t\n", {arithmetic>=geometric and geometric>=harmonic})


<?php
// Created with PHP 7.0

function ArithmeticMean(array $values)
{
    return array_sum($values) / count($values);
}

function GeometricMean(array $values)
{
    return array_product($values) ** (1 / count($values));
}

function HarmonicMean(array $values)
{
    $sum = 0;

    foreach ($values as $value) {
        $sum += 1 / $value;
    }

    return count($values) / $sum;
}

$values = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

echo "Arithmetic: " . ArithmeticMean($values) . "\n";
echo "Geometric: " . GeometricMean($values) . "\n";
echo "Harmonic: " . HarmonicMean($values) . "\n";


(load "@lib/math.l")

(let (Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0)  Len (length Lst))
   (prinl "Arithmetic mean: "
      (format
         (/ (apply + Lst) Len)
         *Scl ) )
   (prinl "Geometric mean: "
      (format
         (pow (*/ (apply * Lst) (** 1.0 (dec Len))) (/ 1.0 Len))
         *Scl ) )
   (prinl "Harmonic mean: "
      (format
         (*/ (* 1.0 Len) 1.0 (sum '((N) (*/ 1.0 1.0 N)) Lst))
         *Scl ) ) )


declare n fixed binary,
        (Average, Geometric, Harmonic) float;
declare A(10) float static initial (1,2,3,4,5,6,7,8,9,10);

n = hbound(A,1);

/* compute the average */
Average = sum(A)/n;

/* Compute the geometric mean: */
Geometric = prod(A)**(1/n);

/* Compute the Harmonic mean: */
Harmonic = n / sum(1/A);

put skip data (Average);
put skip data (Geometric);
put skip data (Harmonic);

if Average < Geometric then put skip list ('Error');
if Geometric < Harmonic then put skip list ('Error');


/pythamean{
/x exch def
/sum 0 def
/prod 1 def
/invsum 0 def
/i 1 def

x{
/sum sum i add def
/prod prod i mul def
/invsum invsum i -1 exp add def
/i i 1 add def
}repeat
(Arithmetic Mean : ) print
sum x div =
(Geometric Mean : ) print
prod x -1 exp exp =
(Harmonic Mean : ) print
x invsum div =
}def

10 pythamean


$A = 0
$LogG = 0
$InvH = 0

$ii = 1..10
foreach($i in $ii) {
	# Arithmetic mean is computed directly
	$A += $i / $ii.Count
	# Geometric mean is computed using Logarithms
	$LogG += [Math]::Log($i) / $ii.Count
	# Harmonic mean is computed using its inverse
	$InvH += 1 / ($i * $ii.Count)
}

$G = [Math]::Exp($LogG)
$H = 1/$InvH

write-host "Arithmetic mean: A = $A"
write-host "Geometric mean:  G = $G"
write-host "Harmonic mean:   H = $H"

write-host "Is A >= G ? $($A -ge $G)"
write-host "Is G >= H ? $($G -ge $H)"


void setup() {
  float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  println("Arithmetic mean: " + arithmeticMean(numbers));
  println("Geometric mean: " + geometricMean(numbers));
  println("Harmonic mean: " + harmonicMean(numbers));
}

float arithmeticMean(float[] nums) {
  float mean = 0;
  for (float n : nums) {
    mean += n;
  }
  mean = mean / nums.length;
  return mean;
}

float geometricMean(float[] nums) {
  float mean = 1;
  for (float n : nums) {
    mean *= n;
  }
  mean = pow(mean, 1.0 / nums.length);
  return mean;
}

float harmonicMean(float[] nums) {
  float mean = 0;
  for (float n : nums) {
    mean += 1 / n;
  }
  mean = nums.length / mean;
  return mean;
}


Procedure.d ArithmeticMean()
  For a = 1 To 10
    mean + a
  Next
  ProcedureReturn mean / 10
EndProcedure
Procedure.d GeometricMean()
  mean = 1
  For a = 1 To 10
    mean * a
  Next
  ProcedureReturn Pow(mean, 1 / 10)
EndProcedure
Procedure.d HarmonicMean()
  For a = 1 To 10
    mean.d + 1 / a
  Next
  ProcedureReturn 10 / mean
EndProcedure

If HarmonicMean() <= GeometricMean() And GeometricMean() <= ArithmeticMean()
  Debug "true"
EndIf
Debug ArithmeticMean()
Debug GeometricMean()
Debug HarmonicMean()


from operator import mul
from functools import reduce

def amean(num):
    return sum(num) / len(num)

def gmean(num):
    return reduce(mul, num, 1)**(1 / len(num))

def hmean(num):
    return len(num) / sum(1 / n for n in num)

numbers = range(1, 11)  # 1..10
a, g, h = amean(numbers), gmean(numbers), hmean(numbers)
print(a, g, h)
assert a >= g >= h


  [] 10 times [ i^ 1+ join ]

  say "Arithmetic mean:" sp
  0 over witheach +
  over size 8 point$ echo$
  cr
  say " Geometric mean:" sp
  1 over witheach *
  over size 80 ** * 10 root
  10 8 ** 8 point$ echo$
  cr
  say "  Harmonic mean:" sp
  dup size dip
    [ 0 n->v rot
      witheach [ n->v 1/v v+ ] ]
  n->v 2swap v/ 8 point$ echo$


#lang racket

(define (arithmetic xs)
  (/ (for/sum ([x xs]) x)
     (length xs)))

(define (geometric xs)
  (expt (for/product ([x xs]) x)
        (/ (length xs))))

(define (harmonic xs)
  (/ (length xs)
     (for/sum ([x xs]) (/ x))))

(define xs (range 1 11))
(arithmetic xs)
(geometric xs)
(harmonic xs)
(>= (arithmetic xs) (geometric xs) (harmonic xs))


/*REXX program  computes and displays the   Pythagorean means  [Amean,  Gmean,  Hmean]. */
numeric digits 20                                /*use a little extra for the precision.*/
parse arg n .                                    /*obtain the optional argument from CL.*/
if n=='' | n==","  then n= 10                    /*None specified?  Then use the default*/
sum= 0;  prod= 1;  rSum= 0                       /*initialize sum/product/reciprocal sum*/
$=;                       do #=1  for n;  $= $ # /*generate list by appending # to list.*/
                          sum = sum   +   #      /*compute the sum of all the elements. */
                          prod= prod  *   #      /*compute the product of all elements. */
                          rSum= rSum  + 1/#      /*compute the sum of the reciprocals.  */
                          end   /*#*/
say ' list ='$                                   /*display the list of numbers used.    */
say 'Amean ='  sum / n                           /*calculate & display  arithmetic mean.*/
say 'Gmean ='  Iroot(prod, n)                    /*    "     "     "    geometric    "  */
if result=="[n/a]"  then say '***error***: root' y "can't be even if 1st argument is < 0."
say 'Hmean ='  n   / rSum                        /*    "     "     "    harmonic     "  */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Iroot: procedure; parse arg x 1 ox, y 1 oy       /*get both args, and also a copy of X&Y*/
       if x=0 | x=1 | y=1  then return x         /*handle special case of zero and unity*/
       if y=0              then return 1         /*   "      "      "   " a   zero root.*/
       if x<0 & y//2==0    then return  '[n/a]'  /*indicate result is "not applicable". */
       x= abs(x);          y= abs(y);   m= y - 1 /*use the absolute value for  X and Y. */
       oDigs= digits();    a= oDigs + 5          /*save original digits;  add five digs.*/
       g= (x+1) / y*2                            /*use this as the first guesstimate.   */
       d= 5                                      /*start with 5 dec digs, saves CPU time*/
           do  until d==a;      d= min(d + d, a) /*keep going as digits are increased.  */
           numeric digits d;    f= d - 2         /*limit digits to  original digits + 5.*/
           og=                                   /*use a non─guess for the old G (guess)*/
              do forever;       gm= g**m         /*keep computing at the   Yth   root.  */
              _= format( (m*g*gm + x)/(y*gm),,f) /*this is the nitty─gritty calculation.*/
              if _=g  |  _=og  then leave        /*are we close enough yet?             */
              og= g;            g= _             /*save guess ──► OG; set the new guess.*/
              end   /*forever*/
           end      /*until  */

       g= g * sign(ox);  if oy<0  then  g= 1 / g /*adjust for original X sign; neg. root*/
       numeric digits oDigs;      return   g / 1 /*normalize to original decimal digits.*/


decimals(8)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
see "arithmetic mean = "  + arithmeticMean(array) + nl
see "geometric mean =  "  + geometricMean(array) + nl
see "harmonic mean =  "  + harmonicMean(array) + nl

func arithmeticMean a
     return summary(a) / len(a)

func geometricMean a
     b = 1
     for i = 1 to len(a)
         b *= a[i]
     next
     return pow(b, (1/len(a)))

func harmonicMean a
     b = list(len(a))
     for nr = 1 to len(a)
         b[nr] = 1/a[nr]
     next
     return len(a) / summary(b)

func summary s
     sum = 0
     for n = 1 to len(s)
         sum += s[n]
     next
     return sum


class Array
  def arithmetic_mean
    inject(0.0, :+) / length
  end

  def geometric_mean
    inject(:*) ** (1.0 / length)
  end

  def harmonic_mean
    length / inject(0.0) {|s, m| s + 1.0/m}
  end
end

class Range
  def method_missing(m, *args)
    case m
    when /_mean$/ then to_a.send(m)
    else super
    end
  end
end

p a = (1..10).arithmetic_mean
p g = (1..10).geometric_mean
p h = (1..10).harmonic_mean
# is h < g < a ??
p g.between?(h, a)


bXsum   = 1
for i   = 1 to 10
  sum   = sum + i                ' sum of 1 -> 10
  bXsum = bXsum * i              ' sum i * i
  sum1i = sum1i + (1/i)          ' sum 1/i
next

average   = sum / 10
geometric = bXsum ^ (1/10)
harmonic  = 10/sum1i

 print "ArithmeticMean:";average
 print "Geometric Mean:";geometric
 print " Harmonic Mean:";harmonic

 if (average >= geometric) and (geometric >= harmonic) then print "True" else print "False"


fn main() {
    let mut sum = 0.0;
    let mut prod = 1;
    let mut recsum = 0.0;
    for i in 1..11{
        sum += i as f32;
        prod *= i;
        recsum += 1.0/(i as f32);
    }
    let avg = sum/10.0;
    let gmean = (prod as f32).powf(0.1);
    let hmean = 10.0/recsum;
    println!("Average: {}, Geometric mean: {}, Harmonic mean: {}", avg, gmean, hmean);
    assert!( ( (avg >= gmean) && (gmean >= hmean) ), "Incorrect calculation");

}


def arithmeticMean(n: Seq[Int]) = n.sum / n.size.toDouble
def geometricMean(n: Seq[Int])  = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.toDouble)
def harmonicMean(n: Seq[Int])   = n.size / n.map(1.0 / _).sum

var nums = 1 to 10
var a = arithmeticMean(nums)
var g = geometricMean(nums)
var h = harmonicMean(nums)

println("Arithmetic mean " + a)
println("Geometric mean  " + g)
println("Harmonic mean   " + h)

assert(a >= g && g >= h)


(define (a-mean l)
  (/ (apply + l) (length l)))

(define (g-mean l)
  (expt (apply * l) (/ (length l))))

(define (h-mean l)
  (/ (length l) (apply + (map / l))))

(define (iota start stop)
  (if (> start stop)
      (list)
      (cons start (iota (+ start 1) stop))))

(let* ((l (iota 1 10)) (a (a-mean l)) (g (g-mean l)) (h (h-mean l)))
  (display a)
  (display " >= ")
  (display g)
  (display " >= ")
  (display h)
  (newline)
  (display (>= a g h))
  (newline))


$ include "seed7_05.s7i";
  include "float.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 proc: main is func
  local
    var float: number is 0.0;
    var float: sum is 0.0;
    var float: product is 1.0;
    var float: reciprocalSum is 0.0;
  begin
    for number range numbers do
      sum +:= number;
      product *:= number;
      reciprocalSum +:= 1.0 / number;
    end for;
    writeln("Arithmetic mean: " <& sum / flt(length(numbers)));
    writeln("Geometric mean:  " <& product ** (1.0 / flt(length(numbers))));
    writeln("Harmonic mean:   " <& flt(length(numbers)) / reciprocalSum);
  end func;


func A(a) { a.sum / a.len }
func G(a) { a.prod.root(a.len) }
func H(a) { a.len / a.map{1/_}.sum }


Collection extend
[
    arithmeticMean
    [
	^ (self fold: [:a :b| a + b ]) / (self size)
    ]

    geometricMean
    [
	^ (self fold: [:a :b| a * b]) raisedTo: (self size reciprocal)
    ]

    harmonicMean
    [
	^ (self size) / ((self collect: [:x|x reciprocal]) fold: [:a :b| a + b ] )
    ]
]

|a|
a := #(1 2 3 4 5 6 7 8 9 10).

a arithmeticMean asFloat displayNl.
a geometricMean asFloat displayNl.
a harmonicMean asFloat displayNl.

((a arithmeticMean) >= (a geometricMean)) displayNl.
((a geometricMean) >= (a harmonicMean)) displayNl.


--setup
CREATE TABLE averages (val INTEGER);
INSERT INTO averages VALUES (1);
INSERT INTO averages VALUES (2);
INSERT INTO averages VALUES (3);
INSERT INTO averages VALUES (4);
INSERT INTO averages VALUES (5);
INSERT INTO averages VALUES (6);
INSERT INTO averages VALUES (7);
INSERT INTO averages VALUES (8);
INSERT INTO averages VALUES (9);
INSERT INTO averages VALUES (10);
-- calculate means
SELECT
  1/avg(1/val) AS harm,
  avg(val) AS arith
FROM
  averages;


proc arithmeticMean list {
    set sum 0.0
    foreach value $list { set sum [expr {$sum + $value}] }
    return [expr {$sum / [llength $list]}]
}
proc geometricMean list {
    set product 1.0
    foreach value $list { set product [expr {$product * $value}] }
    return [expr {$product ** (1.0/[llength $list])}]
}
proc harmonicMean list {
    set sum 0.0
    foreach value $list { set sum [expr {$sum + 1.0/$value}] }
    return [expr {[llength $list] / $sum}]
}

set nums {1 2 3 4 5 6 7 8 9 10}
set A10 [arithmeticMean $nums]
set G10 [geometricMean $nums]
set H10 [harmonicMean $nums]
puts "A10=$A10, G10=$G10, H10=$H10"
if {$A10 >= $G10} { puts "A10 >= G10" }
if {$G10 >= $H10} { puts "G10 >= H10" }


#import std
#import flo

data = ari10(1.,10.)   # arithmetic progression, length 10 with endpoints 1 and 10

a = mean data
g = exp mean ln* data
h = div/1. mean div/*1. data

#cast %eLbX

main = ^(~&,ordered not fleq) <a,g,h>


double arithmetic(int[] list){
	double mean;
	double sum = 0;
	foreach(int number in list){
		sum += number;
	} // foreach

	mean = sum / list.length;

	return mean;
} // end arithmetic mean

double geometric(int[] list){
	double mean;
	double product = 1;
	foreach(int number in list){
		product *= number;
	} // foreach

	mean = Math.pow(product, (1 / (double) list.length));

	return mean;
} // end geometric mean

double harmonic(int[] list){
	double mean;
	double sum_inverse = 0;
	foreach(int number in list){
		sum_inverse += (1 / (double) number);
	} // foreach

	mean = (double) list.length / sum_inverse;

	return mean;
} // end harmonic mean

public static void main(){
	int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

	double arithmetic_mean = arithmetic(list);
	double geometric_mean = geometric(list);
	double harmonic_mean = harmonic(list);

	// should be 5.5
	stdout.printf("Arithmetic mean: %s\n", arithmetic_mean.to_string());

	// should be 4.528728688116765
	stdout.printf("Geometric mean: %s\n", geometric_mean.to_string());

	// should be 4.528728688116765
	stdout.printf("Harmonic mean: %s\n", harmonic_mean.to_string());
}


Private Function arithmetic_mean(s() As Variant) As Double
    arithmetic_mean = WorksheetFunction.Average(s)
End Function
Private Function geometric_mean(s() As Variant) As Double
    geometric_mean = WorksheetFunction.GeoMean(s)
End Function
Private Function harmonic_mean(s() As Variant) As Double
    harmonic_mean = WorksheetFunction.HarMean(s)
End Function
Public Sub pythagorean_means()
    Dim s() As Variant
    s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
    Debug.Print "A ="; arithmetic_mean(s)
    Debug.Print "G ="; geometric_mean(s)
    Debug.Print "H ="; harmonic_mean(s)
End Sub


Function arithmetic_mean(arr)
	sum = 0
	For i = 0 To UBound(arr)
		sum = sum + arr(i)
	Next
	arithmetic_mean = sum / (UBound(arr)+1)
End Function

Function geometric_mean(arr)
	product = 1
	For i = 0 To UBound(arr)
		product = product * arr(i)
	Next
	geometric_mean = product ^ (1/(UBound(arr)+1))
End Function

Function harmonic_mean(arr)
	sum = 0
	For i = 0 To UBound(arr)
		sum = sum + (1/arr(i))
	Next
	harmonic_mean = (UBound(arr)+1) / sum
End Function

WScript.StdOut.WriteLine arithmetic_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10))
WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10))


Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Function Gmean(n As IEnumerable(Of Double)) As Double
        Return Math.Pow(n.Aggregate(Function(s, i) s * i), 1.0 / n.Count())
    End Function

    <Extension()>
    Function Hmean(n As IEnumerable(Of Double)) As Double
        Return n.Count() / n.Sum(Function(i) 1.0 / i)
    End Function

    Sub Main()
        Dim nums = From n In Enumerable.Range(1, 10) Select CDbl(n)

        Dim a = nums.Average()
        Dim g = nums.Gmean()
        Dim h = nums.Hmean()

        Console.WriteLine("Arithmetic mean {0}", a)
        Console.WriteLine(" Geometric mean {0}", g)
        Console.WriteLine("  Harmonic mean {0}", h)
        Debug.Assert(a >= g AndAlso g >= h)
    End Sub

End Module


import math

fn main() {
    mut sum := 0.0
    mut prod :=1.0
    mut recip_sum := 0.0
    n := 10

    for val in 1..(n + 1) {
        sum += val
        prod *= val
        recip_sum = recip_sum + ( 1.0 / val )
    }

    a := sum / n
    g := math.pow( prod, ( 1.0 / f32(n) ) )
    h := n / recip_sum

    result := 'Arithmetic Mean: ${a:3.2f} \nGeometric Mean: ${g:3.2f}\nHarmonic Mean: ${h:3.2f}'
    println( result )

    compare := if a >= g && g >= h { "Yes" } else { "Nope" }
    println('Is A >= G >= H? $compare')
}


var rng = 1..10
var count = rng.count
var A = rng.reduce { |acc, x| acc + x }/count
var G = rng.reduce { |prod, x| prod * x}.pow(1/count)
var H = rng.reduce { |acc, x| acc + 1/x}.pow(-1) * count

System.print("For the numbers %(rng):")
System.print("  Arithmetic mean = %(A)")
System.print("  Geometric mean  = %(G)")
System.print("  Harmonic mean   = %(H)")
System.print("  A >= G >= H     = %(A >= G && G >= H)")


include c:\cxpl\codes;

func real Power(X, Y);          \X raised to the Y power
real X, Y;                      \ (from StdLib.xpl)
return Exp(Y * Ln(X));

int  N, Order;
real R, A, A1, G, G1, H, H1;
[A1:= 0.0;  G1:= 1.0;  H1:= 0.0;
Order:= true;
for N:= 1 to 10 do
        [R:= float(N);          \convert integer N to real R
        A1:= A1 + R;
        A:= A1/R;               \arithmetic mean
        G1:= G1 * R;
        G:= Power(G1, 1.0/R);   \geometric mean (Nth root of G1)
        if G>A then Order:= false;
        H1:= H1 + 1.0/R;
        H:= R/H1;               \harmonic mean
        if H>G then Order:= false;
        ];
RlOut(0, A); CrLf(0);
RlOut(0, G); CrLf(0);
RlOut(0, H); CrLf(0);
if not Order then Text(0, "NOT ");
Text(0, "ALWAYS DECREASING ORDER
");
]


ns:=T(1,2,3,4,5,6,7,8,9,10);
ns.sum(0.0)/ns.len();					   // Arithmetic mean
ns.reduce('*,1.0).pow(1.0/ns.len());			   // Geometric mean
ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean


*        Find the lowest positive integer whose square ends in 269696
*        The logic of the assembler program is simple :
*        loop for i=524 step 2
*          if (i*i modulo 1000000)=269696 then leave loop
*        next i
*        output 'Solution is: i=' i '  (i*i=' i*i ')'
BABBAGE  CSECT                     beginning of the control section
         USING BABBAGE,13          define the base register
         B     72(15)              skip savearea (72=18*4)
         DC    17F'0'              savearea (18 full words (17+1))
         STM   14,12,12(13)        prolog: save the caller registers
         ST    13,4(15)            prolog: link backwards
         ST    15,8(13)            prolog: link forwards
         LR    13,15               prolog: establish addressability
         LA    6,524               let register6 be i and load 524
LOOP     LR    5,6                 load register5 with i
         MR    4,6                 multiply register5 with i
         LR    7,5                 load register7 with the result i*i
         D     4,=F'1000000'       divide register5 with 1000000
         C     4,=F'269696'        compare the reminder with 269696
         BE    ENDLOOP             if equal branch to ENDLOOP
         LA    6,2(6)              load register6 (i) with value i+2
         B     LOOP                branch to LOOP
ENDLOOP  XDECO 6,BUFFER+15         edit registrer6 (i)
         XDECO 7,BUFFER+34         edit registrer7 (i squared)
         XPRNT BUFFER,L'BUFFER     print buffer
         L     13,4(0,13)          epilog: restore the caller savearea
         LM    14,12,12(13)        epilog: restore the caller registers
         XR    15,15               epilog: set return code to 0
         BR    14                  epilog: branch to caller
BUFFER   DC    CL80'Solution is: i=............  (i*i=............)'
         END   BABBAGE             end of the control section


-- The program is written in the programming language Ada. The name "Ada"
-- has been chosen in honour of your friend,
--      Augusta Ada King-Noel, Countess of Lovelace (née Byron).
--
-- This is an program to search for the smallest integer X, such that
-- (X*X) mod 1_000_000 = 269_696.
--
-- In the Ada language, "*" represents the multiplication symbol, "mod" the
-- modulo reduction, and the underscore "_" after every third digit in
-- literals is supposed to simplify reading numbers for humans.
-- Everything written after "--" in a line is a comment for the human,
-- and will be ignored by the computer.

with Ada.Text_IO;
-- We need this to tell the computer how it will later output its result.

procedure Babbage_Problem is

   -- We know that 99_736*99_736 is 9_947_269_696. This implies:
   -- 1. The smallest X with X*X mod 1_000_000 = 269_696 is at most 99_736.
   -- 2. The largest square X*X, which the program may have to deal with,
   --    will be at most 9_947_269_69.

   type Number is range 1 .. 99_736*99_736;
   X: Number := 1;
   -- X can store numbers between 1 and 99_736*99_736. Computations
   -- involving X can handle intermediate results in that range.
   -- Initially the value stored at X is 1.
   -- When running the program, the value will become 2, 3, 4, etc.

begin
   -- The program starts running.

   -- The computer first squares X, then it truncates the square, such
   -- that the result is a six-digit number.
   -- Finally, the computer checks if this number is 269_696.
   while not (((X*X) mod 1_000_000) = 269_696) loop

      -- When the computer goes here, the number was not 269_696.
      X := X+1;
      -- So we replace X by X+1, and then go back and try again.

   end loop;

   -- When the computer eventually goes here, the number is 269_696.
   -- E.e., the value stored at X is the value we are searching for.
   -- We still have to print out this value.

   Ada.Text_IO.Put_Line(Number'Image(X));
   -- Number'Image(X) converts the value stored at X into a string of
   -- printable characters (more specifically, of digits).
   -- Ada.Text_IO.Put_Line(...) prints this string, for humans to read.
   -- I did already run the program, and it did print out 25264.
end Babbage_Problem;