fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }

fun main(args: Array<String>) {
    median(listOf(5.0, 3.0, 4.0)).let { println(it) }  // 4
    median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) }  // 3.5
    median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) }  // 2.1
}


define median_ext(a::array) => {
	#a->sort

	if(#a->size % 2) => {
		// odd numbered element array, pick middle
		return #a->get(#a->size / 2 + 1)

	else
		// even number elements in array
		return (#a->get(#a->size / 2) + #a->get(#a->size / 2 + 1)) / 2.0
	}
}

median_ext(array(3,2,7,6)) // 4.5
median_ext(array(3,2,9,7,6)) // 6


    dim a( 100), b( 100)    '   assumes we will not have vectors of more terms...

    a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2"
    print "Median is "; median( a$)        '   4.4   7 terms
    print
    a$ ="4.1,7.2,1.7,9.3,4.4,3.2"
    print "Median  is "; median( a$)        '   4.25  6 terms
    print
    a$ ="4.1,4,1.2,6.235,7868.33"   '   4.1
    print "Median of "; a$; " is "; median( a$)
    print
    a$ ="1,5,3,2,4"             '   3
    print "Median of "; a$; " is "; median( a$)
    print
    a$ ="1,5,3,6,4,2"          '   3.5
    print "Median of "; a$; " is "; median( a$)
    print
    a$ ="4.4,2.3,-1.7,7.5,6.6,0.0,1.9,8.2,9.3,4.5" '   4.45
    print "Median of "; a$; " is "; median( a$)

    end

    function median( a$)
        i =1
        do
            v$     =word$( a$, i, ",")
            if v$ ="" then exit do
            print v$,
            a( i)  =val( v$)
            i      =i +1
        loop until 0
        print

        sort a(), 1, i -1

        for j =1 to i -1
            print a( j),
        next j
        print

        middle    =( i -1) /2
        intmiddle =int( middle)
        if middle <>intmiddle then median= a( 1 +intmiddle) else median =( a( intmiddle) +a( intmiddle +1)) /2
    end function


on median (numlist)
    -- numlist = numlist.duplicate() -- if input list should not be altered
    numlist.sort()
    if numlist.count mod 2 then
        return numlist[numlist.count/2+1]
    else
        return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0
    end if
end


integer MAX_ELEMENTS = 10;
integer MAX_VALUE = 100;
default {
    state_entry() {
        list lst = [];
        integer x = 0;
        for(x=0 ; x<MAX_ELEMENTS ; x++) {
            lst += llFrand(MAX_VALUE);
        }
        llOwnerSay("lst=["+llList2CSV(lst)+"]");
        llOwnerSay("Geometric Mean: "+(string)llListStatistics(LIST_STAT_GEOMETRIC_MEAN, lst));
        llOwnerSay("           Max: "+(string)llListStatistics(LIST_STAT_MAX, lst));
        llOwnerSay("          Mean: "+(string)llListStatistics(LIST_STAT_MEAN, lst));
        llOwnerSay("        Median: "+(string)llListStatistics(LIST_STAT_MEDIAN, lst));
        llOwnerSay("           Min: "+(string)llListStatistics(LIST_STAT_MIN, lst));
        llOwnerSay("     Num Count: "+(string)llListStatistics(LIST_STAT_NUM_COUNT, lst));
        llOwnerSay("         Range: "+(string)llListStatistics(LIST_STAT_RANGE, lst));
        llOwnerSay("       Std Dev: "+(string)llListStatistics(LIST_STAT_STD_DEV, lst));
        llOwnerSay("           Sum: "+(string)llListStatistics(LIST_STAT_SUM, lst));
        llOwnerSay("   Sum Squares: "+(string)llListStatistics(LIST_STAT_SUM_SQUARES, lst));
    }
}


function median (numlist)
    if type(numlist) ~= 'table' then return numlist end
    table.sort(numlist)
    if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
    return numlist[math.ceil(#numlist/2)]
end

print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))


function medianValue = findmedian(setOfValues)
   medianValue = median(setOfValues);
end


list.median = function()
    self.sort
    m = floor(self.len/2)
    if self.len % 2 then return self[m]
    return (self[m] + self[m-1]) * 0.5
end function

print [41, 56, 72, 17, 93, 44, 32].median
print [41, 72, 17, 93, 44, 32].median


MEDIAN(X)
 ;X is assumed to be a list of numbers separated by "^"
 ;I is a loop index
 ;L is the length of X
 ;Y is a new array
 QUIT:'$DATA(X) "No data"
 QUIT:X="" "Empty Set"
 NEW I,ODD,L,Y
 SET L=$LENGTH(X,"^"),ODD=L#2,I=1
 ;The values in the vector are used as indices for a new array Y, which sorts them
 FOR  QUIT:I>L  SET Y($PIECE(X,"^",I))=1,I=I+1
 ;Go to the median index, or the lesser of the middle if there is an even number of elements
 SET J="" FOR I=1:1:$SELECT(ODD:L\2+1,'ODD:L/2) SET J=$ORDER(Y(J))
 QUIT $SELECT(ODD:J,'ODD:(J+$ORDER(Y(J)))/2)


import sort

def median(aray)
	srtd = sort(aray)
	alen = len(srtd)
	return 0.5*( srtd[int(alen-1/2)] + srtd[int(alen/2)])
end

a = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}
println a + " " + median(a)
a = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2}
println a + " " + median(a)


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

class RAvgMedian00 public

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method median(lvector = java.util.List) public static returns Rexx
    cvector = ArrayList(lvector) -- make a copy of input to ensure it's contents are preserved
    Collections.sort(cvector, RAvgMedian00.RexxComparator())
    kVal = ((Rexx cvector.get(cvector.size() % 2)) + (Rexx cvector.get((cvector.size() - 1) % 2))) / 2
    return kVal

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method median(rvector = Rexx[]) public static returns Rexx
    return median(ArrayList(Arrays.asList(rvector)))

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method show_median(lvector = java.util.List) public static returns Rexx
    mVal = median(lvector)
    say 'Meadian:' mVal.format(10, 6, 3, 6, 's')', Vector:' (Rexx lvector).space(0)
    return mVal

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method show_median(rvector = Rexx[]) public static returns Rexx
    return show_median(ArrayList(Arrays.asList(rvector)))

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method run_samples() public static
    show_median([Rexx 10.0])                                                   -- 10.0
    show_median([Rexx 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0])      -- 5.5
    show_median([Rexx 9, 8, 7, 6, 5, 4, 3, 2, 1])                              -- 5.0
    show_median([Rexx 1.0, 9, 2.0, 4.0])                                       -- 3.0
    show_median([Rexx 3.0, 1, 4, 1.0, 5.0, 9, 7.0, 6.0])                       -- 4.5
    show_median([Rexx 3, 4, 1, -8.4, 7.2, 4, 1, 1.2])                          -- 2.1
    show_median([Rexx -1.2345678e+99, 2.3e+700])                               -- 1.15e+700
    show_median([Rexx 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])                      -- 4.4
    show_median([Rexx 4.1, 7.2, 1.7, 9.3, 4.4, 3.2])                           -- 4.25
    show_median([Rexx 28.207, 74.916, 51.695, 72.486, 51.118, 3.241, 73.807])  -- 51.695
    show_median([Rexx 27.984, 89.172, 0.250, 66.316, 41.805, 60.043])          -- 50.924
    show_median([Rexx 5.1, 2.6, 6.2, 8.8, 4.6, 4.1])                           -- 4.85
    show_median([Rexx 5.1, 2.6, 8.8, 4.6, 4.1])                                -- 4.6
    show_median([Rexx 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])      -- 4.45
    show_median([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11])        -- 3.0
    show_median([Rexx 10, 20, 30, 40, 50, -100, 4.7, -11e+2])                  -- 15.0
    show_median([Rexx 9.3, -2.0, 4.0, 7.3, 8.1, 4.1, -6.3, 4.2, -1.0, -8.4])   -- 4.05
    show_median([Rexx 8.3, -3.6, 5.7, 2.3, 9.3, 5.4, -2.3, 6.3, 9.9])          -- 5.7
    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method main(args = String[]) public static
    run_samples()
    return

-- =============================================================================
class RAvgMedian00.RexxComparator implements Comparator

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method compare(i1=Object, i2=Object) public returns int
    i = Rexx i1
    j = Rexx i2

    if i < j then return -1
    if i > j then return +1
    else return 0


; median.lsp
; oofoe 2012-01-25

(define (median lst)
  (sort lst) ; Sorts in place.
  (if (empty? lst)
      nil
    (letn ((n (length lst))
           (h (/ (- n 1) 2)))
          (if (zero? (mod n 2))
              (div (add (lst h) (lst (+ h 1))) 2)
            (lst h))
          )))

(define (test lst) (println lst " -> " (median lst)))

(test '())
(test '(5 3 4))
(test '(5 4 2 3))
(test '(3 4 1 -8.4 7.2 4 1 1.2))

(exit)


import algorithm, strutils

proc median(xs: seq[float]): float =
  var ys = xs
  sort(ys, system.cmp[float])
  0.5 * (ys[ys.high div 2] + ys[ys.len div 2])

var a = @[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
echo formatFloat(median(a), precision = 0)
a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2]
echo formatFloat(median(a), precision = 0)


MODULE Median;
IMPORT Out;
CONST
	MAXSIZE = 100;

PROCEDURE Partition(VAR a: ARRAY OF REAL; left, right: INTEGER): INTEGER;
VAR
	pValue,aux: REAL;
	store,i,pivot: INTEGER;
BEGIN
	pivot := right;
	pValue := a[pivot];
	aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *)
	store := left;
	FOR i := left TO right -1 DO
		IF a[i] <= pValue THEN
			aux := a[store];a[store] := a[i];a[i]:=aux;
			INC(store)
		END
	END;
	aux := a[right];a[right] := a[store]; a[store] := aux;
	RETURN store
END Partition;

(* QuickSelect algorithm *)
PROCEDURE Select(a: ARRAY OF REAL; left,right,k: INTEGER;VAR r: REAL);
VAR
	pIndex, pDist : INTEGER;
BEGIN
	IF left = right THEN r := a[left]; RETURN END;
	pIndex := Partition(a,left,right);
	pDist := pIndex - left + 1;
	IF pDist = k THEN
		r := a[pIndex];RETURN
	ELSIF k < pDist THEN
		Select(a,left, pIndex - 1, k, r)
	ELSE
		Select(a,pIndex + 1, right, k - pDist, r)
	END
END Select;

PROCEDURE Median(a: ARRAY OF REAL;left,right: INTEGER): REAL;
VAR
	idx,len : INTEGER;
	r1,r2 : REAL;
BEGIN
	len := right - left + 1;
	idx := len DIV 2 + 1;
	r1 := 0.0;r2 := 0.0;
	Select(a,left,right,idx,r1);
	IF ODD(len) THEN RETURN r1 END;
	Select(a,left,right,idx - 1,r2);
	RETURN (r1 + r2) / 2;
END Median;

VAR
	ary: ARRAY MAXSIZE OF REAL;
	r: REAL;
BEGIN
	r := 0.0;
	Out.Fixed(Median(ary,0,0),4,2);Out.Ln;	(* empty *)
	ary[0] := 5;
	ary[1] := 3;
	ary[2] := 4;
	Out.Fixed(Median(ary,0,2),4,2);Out.Ln;
	ary[0] := 5;
	ary[1] := 4;
	ary[2] := 2;
	ary[3] := 3;
	Out.Fixed(Median(ary,0,3),4,2);Out.Ln;
	ary[0] := 3;
	ary[1] := 4;
	ary[2] := 1;
	ary[3] := -8.4;
	ary[4] := 7.2;
	ary[5] := 4;
	ary[6] := 1;
	ary[7] := 1.2;
	Out.Fixed(Median(ary,0,7),4,2);Out.Ln;
END Median.


use Structure;

bundle Default {
  class Median {
    function : Main(args : String[]) ~ Nil {
      numbers := FloatVector->New([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]);
      DoMedian(numbers)->PrintLine();

      numbers := FloatVector->New([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]);
      DoMedian(numbers)->PrintLine();
    }

    function : native : DoMedian(numbers : FloatVector) ~ Float {
      if(numbers->Size() = 0) {
        return 0.0;
      }
      else if(numbers->Size() = 1) {
        return numbers->Get(0);
      };

      numbers->Sort();

      i := numbers->Size() / 2;
      if(numbers->Size() % 2 = 0) {
        return (numbers->Get(i - 1) + numbers->Get(i)) / 2.0;
      };

      return numbers->Get(i);
    }
  }
}


(* note: this modifies the input array *)
let median array =
  let len = Array.length array in
    Array.sort compare array;
    (array.((len-1)/2) +. array.(len/2)) /. 2.0;;

let a = [|4.1; 5.6; 7.2; 1.7; 9.3; 4.4; 3.2|];;
median a;;
let a = [|4.1; 7.2; 1.7; 9.3; 4.4; 3.2|];;
median a;;


function y = median2(v)
  if (numel(v) < 1)
    y = NA;
  else
    sv = sort(v);
    l = numel(v);
    if ( mod(l, 2) == 0 )
      y = (sv(floor(l/2)+1) + sv(floor(l/2)))/2;
    else
      y = sv(floor(l/2)+1);
    endif
  endif
endfunction

a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2];
b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2];

disp(median2(a))   % 4.4
disp(median(a))
disp(median2(b))   % 4.25
disp(median(b))


call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testMedian .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2)
call testMedian .array~new

::routine testMedian
  use arg numbers
  say "numbers =" numbers~toString("l", ", ")
  say "median =" median(numbers)
  say

::routine median
  use arg numbers

  if numbers~isempty then return 0
  -- make a copy so the sort does not alter the
  -- original set.  This also means this will
  -- work with lists and queues as well
  numbers = numbers~makearray

  -- sort and return the middle element
  numbers~sortWith(.numbercomparator~new)
  size = numbers~items
  -- this handles the odd value too
  return numbers[size%2 + size//2]

-- a custom comparator that sorts strings as numeric values rather than
-- strings
::class numberComparator subclass comparator
::method compare
  use strict arg left, right
  -- perform the comparison on the names.  By subtracting
  -- the two and returning the sign, we give the expected
  -- results for the compares
  return (left - right)~sign


F mean_angle(angles)
   V x = sum(angles.map(a -> cos(radians(a)))) / angles.len
   V y = sum(angles.map(a -> sin(radians(a)))) / angles.len
   R degrees(atan2(y, x))

print(mean_angle([350, 10]))
print(mean_angle([90, 180, 270, 360]))
print(mean_angle([10, 20, 30]))


declare
  fun {Median Xs}
     Len = {Length Xs}
     Mid = Len div 2 + 1 %% 1-based index
     Sorted = {Sort Xs Value.'<'}
  in
     if {IsOdd Len} then {Nth Sorted Mid}
     else ({Nth Sorted Mid} + {Nth Sorted Mid-1}) / 2.0
     end
  end
in
  {Show {Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2]}}
  {Show {Median [4.1 7.2 1.7 9.3 4.4 3.2]}}


Program AveragesMedian(output);

type
  TDoubleArray = array of double;

procedure bubbleSort(var list: TDoubleArray);
var
  i, j, n: integer;
  t: double;
begin
  n := length(list);
  for i := n downto 2 do
    for j := 0 to i - 1 do
      if list[j] > list[j + 1] then
      begin
        t := list[j];
        list[j] := list[j + 1];
        list[j + 1] := t;
      end;
end;

function Median(aArray: TDoubleArray): double;
var
  lMiddleIndex: integer;
begin
  bubbleSort(aArray);
  lMiddleIndex := (high(aArray) - low(aArray)) div 2;
  if Odd(Length(aArray)) then
    Median := aArray[lMiddleIndex + 1]
  else
    Median := (aArray[lMiddleIndex + 1] + aArray[lMiddleIndex]) / 2;
end;

var
  A: TDoubleArray;
  i: integer;

begin
  randomize;
  setlength(A, 7);
  for i := low(A) to high(A) do
  begin
    A[i] := 100 * random;
    write (A[i]:7:3, ' ');
  end;
  writeln;
  writeln('Median: ', Median(A):7:3);

  setlength(A, 6);
  for i := low(A) to high(A) do
  begin
    A[i] := 100 * random;
    write (A[i]:7:3, ' ');
  end;
  writeln;
  writeln('Median: ', Median(A):7:3);
end.


with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      -- or more digits for improved precision
   subtype Real is X_Real range 0.0 .. 360.0; -- the range of interest
   type Angles is array(Positive range <>) of Real;

   procedure Put(R: Real) is
      package IO is new Ada.Text_IO.Float_IO(Real);
   begin
      IO.Put(R, Fore => 3, Aft => 2, Exp => 0);
   end Put;

   function Mean_Angle(A: Angles) return Real is
      Sin_Sum, Cos_Sum: X_Real := 0.0; -- X_Real since sums might exceed 360.0
      package Math is new Ada.Numerics.Generic_Elementary_Functions(Real);
      use Math;
   begin
      for I in A'Range loop
        Sin_Sum := Sin_Sum + Sin(A(I), Cycle => 360.0);
        Cos_Sum := Cos_Sum + Cos(A(I), Cycle => 360.0);
      end loop;
      return Arctan(Sin_Sum / X_Real(A'Length), Cos_Sum / X_Real(A'Length),
                    Cycle => 360.0);
        -- may raise Ada.Numerics.Argument_Error if inputs are
        -- numerically instable, e.g., when Cos_Sum is 0.0
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    -- 20.00
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    --  0.00
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); -- Ada.Numerics.Argument_Error!
end Mean_Angles;


real
mean(list l)
{
    integer i;
    real x, y;

    x = y = 0;

    i = 0;
    while (i < l_length(l)) {
        x += Gcos(l[i]);
        y += Gsin(l[i]);
        i += 1;
    }

    return Gatan2(y / l_length(l), x / l_length(l));
}

integer
main(void)
{
    o_form("mean of 1st set: /d6/\n", mean(l_effect(350, 10)));
    o_form("mean of 2nd set: /d6/\n", mean(l_effect(90, 180, 270, 360)));
    o_form("mean of 3rd set: /d6/\n", mean(l_effect(10, 20, 30)));

    return 0;
}


#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

PROC mean angle = ([]#LONG# REAL angles)#LONG# REAL:
(
  INT size = UPB angles - LWB angles + 1;
  #LONG# REAL y part := 0, x part := 0;
  FOR i FROM LWB angles TO UPB angles DO
      x part +:= #long# cos (angles[i] * #long# pi / 180);
      y part +:= #long# sin (angles[i] * #long# pi / 180)
  OD;

  #long# arc tan2 (y part / size, x part / size) * 180 / #long# pi
);

main:
(
  []#LONG# REAL angle set 1 = ( 350, 10 );
  []#LONG# REAL angle set 2 = ( 90, 180, 270, 360);
  []#LONG# REAL angle set 3 = ( 10, 20, 30);

  FORMAT summary fmt=$"Mean angle for "g" set :"-zd.ddddd" degrees"l$;
  printf ((summary fmt,"1st", mean angle (angle set 1)));
  printf ((summary fmt,"2nd", mean angle (angle set 2)));
  printf ((summary fmt,"3rd", mean angle (angle set 3)))
)


with javascript_semantics
function median(sequence s)
    atom res=0
    integer l = length(s), k = floor((l+1)/2)
    if l then
        s = sort(s)
        res = s[k]
        if remainder(l,2)=0 then
            res = (res+s[k+1])/2
        end if
    end if
    return res
end function


include ..\Utilitys.pmt

def median  /# l -- n #/
    sort len 2 / >ps
    tps .5 + int 2 slice nip
    ps> dup int != if
        1 get nip
    else
        sum 2 /
    endif
enddef

( 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ) median ?
( 4.1 7.2 1.7 9.3 4.4 3.2 ) median ?


Angles :=  [[350, 10], [90, 180, 270, 360], [10, 20, 30]]
MsgBox, % MeanAngle(Angles[1]) "`n"
	. MeanAngle(Angles[2]) "`n"
	. MeanAngle(Angles[3])

MeanAngle(a, x=0, y=0) {
	static c := ATan(1) / 45
	for k, v in a {
		x += Cos(v * c) / a.MaxIndex()
		y += Sin(v * c) / a.MaxIndex()
	}
	return atan2(x, y) / c
}

atan2(x, y) {
   return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double")
}


function median($arr)
{
    sort($arr);
    $count = count($arr); //count the number of values in array
    $middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
    if ($count % 2) { // odd number, middle is the median
        $median = $arr[$middleval];
    } else { // even number, calculate avg of 2 medians
        $low = $arr[$middleval];
        $high = $arr[$middleval+1];
        $median = (($low+$high)/2);
    }
    return $median;
}

echo median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n";  // 4.4
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n";       // 4.25


(de median (Lst)
   (let N (length Lst)
      (if (bit? 1 N)
         (get (sort Lst) (/ (inc N) 2))
         (setq Lst (nth (sort Lst) (/ N 2)))
         (/ (+ (car Lst) (cadr Lst)) 2) ) ) )

(scl 2)
(prinl (round (median (1.0 2.0 3.0))))
(prinl (round (median (1.0 2.0 3.0 4.0))))
(prinl (round (median (5.1 2.6 6.2 8.8 4.6 4.1))))
(prinl (round (median (5.1 2.6 8.8 4.6 4.1))))


      *FLOAT 64
      DIM angles(3)
      angles() = 350,10
      PRINT FNmeanangle(angles(), 2)
      angles() = 90,180,270,360
      PRINT FNmeanangle(angles(), 4)
      angles() = 10,20,30
      PRINT FNmeanangle(angles(), 3)
      END

      DEF FNmeanangle(angles(), N%)
      LOCAL I%, sumsin, sumcos
      FOR I% = 0 TO N%-1
        sumsin += SINRADangles(I%)
        sumcos += COSRADangles(I%)
      NEXT
      = DEGFNatan2(sumsin, sumcos)

      DEF FNatan2(y,x) : ON ERROR LOCAL = SGN(y)*PI/2
      IF x>0 THEN = ATN(y/x) ELSE IF y>0 THEN = ATN(y/x)+PI ELSE = ATN(y/x)-PI


#include<math.h>
#include<stdio.h>

double
meanAngle (double *angles, int size)
{
  double y_part = 0, x_part = 0;
  int i;

  for (i = 0; i < size; i++)
    {
      x_part += cos (angles[i] * M_PI / 180);
      y_part += sin (angles[i] * M_PI / 180);
    }

  return atan2 (y_part / size, x_part / size) * 180 / M_PI;
}

int
main ()
{
  double angleSet1[] = { 350, 10 };
  double angleSet2[] = { 90, 180, 270, 360};
  double angleSet3[] = { 10, 20, 30};

  printf ("\nMean Angle for 1st set : %lf degrees", meanAngle (angleSet1, 2));
  printf ("\nMean Angle for 2nd set : %lf degrees", meanAngle (angleSet2, 4));
  printf ("\nMean Angle for 3rd set : %lf degrees\n", meanAngle (angleSet3, 3));
  return 0;
}


using System;
using System.Linq;
using static System.Math;
class Program
{
    static double MeanAngle(double[] angles)
    {
        var x = angles.Sum(a => Cos(a * PI / 180)) / angles.Length;
        var y = angles.Sum(a => Sin(a * PI / 180)) / angles.Length;
        return Atan2(y, x) * 180 / PI;
    }
    static void Main()
    {
        Action<double[]> printMean = x => Console.WriteLine("{0:0.###}", MeanAngle(x));
        printMean(new double[] { 350, 10 });
        printMean(new double[] { 90, 180, 270, 360 });
        printMean(new double[] { 10, 20, 30 });
    }
}


call sort(A);
n = dimension(A,1);
if iand(n,1) = 1 then /* an odd number of elements */
   median = A(n/2);
else                  /* an even number of elements */
   median = (a(n/2) + a(trunc(n/2)+1) )/2;


function Measure-Data
{
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [double[]]
        $Data
    )

    Begin
    {
        function Get-Mode ([double[]]$Data)
        {
            if ($Data.Count -gt ($Data | Select-Object -Unique).Count)
            {
                $groups = $Data | Group-Object | Sort-Object -Property Count -Descending

                return ($groups | Where-Object {[double]$_.Count -eq [double]$groups[0].Count}).Name | ForEach-Object {[double]$_}
            }
            else
            {
                return $null
            }
        }

        function Get-StandardDeviation ([double[]]$Data)
        {
            $variance = 0
            $average  = $Data | Measure-Object -Average | Select-Object -Property Count, Average

            foreach ($number in $Data)
            {
                $variance +=  [Math]::Pow(($number - $average.Average),2)
            }

            return [Math]::Sqrt($variance / ($average.Count-1))
        }

        function Get-Median ([double[]]$Data)
        {
            if ($Data.Count % 2)
            {
                return $Data[[Math]::Floor($Data.Count/2)]
            }
            else
            {
                return ($Data[$Data.Count/2], $Data[$Data.Count/2-1] | Measure-Object -Average).Average
            }
        }
    }
    Process
    {
        $Data = $Data | Sort-Object

        $Data | Measure-Object -Maximum -Minimum -Sum -Average |
                Select-Object -Property Count,
                                        Sum,
                                        Minimum,
                                        Maximum,
                                        @{Name='Range'; Expression={$_.Maximum - $_.Minimum}},
                                        @{Name='Mean' ; Expression={$_.Average}} |
                Add-Member -MemberType NoteProperty -Name Median            -Value (Get-Median $Data)            -PassThru |
                Add-Member -MemberType NoteProperty -Name StandardDeviation -Value (Get-StandardDeviation $Data) -PassThru |
                Add-Member -MemberType NoteProperty -Name Mode              -Value (Get-Mode $Data)              -PassThru
    }
}


#include <iomanip>
#include <iostream>
#include <vector>

#define _USE_MATH_DEFINES
#include <math.h>

template<typename C>
double meanAngle(const C& c) {
    auto it = std::cbegin(c);
    auto end = std::cend(c);

    double x = 0.0;
    double y = 0.0;
    double len = 0.0;
    while (it != end) {
        x += cos(*it * M_PI / 180);
        y += sin(*it * M_PI / 180);
        len++;

        it = std::next(it);
    }

    return atan2(y, x) * 180 / M_PI;
}

void printMean(std::initializer_list<double> init) {
    std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\n';
}

int main() {
    printMean({ 350, 10 });
    printMean({ 90, 180, 270, 360 });
    printMean({ 10, 20, 30 });

    return 0;
}


(defn mean-fn
  [k coll]
  (let [n (count coll)
        trig (get {:sin #(Math/sin %) :cos #(Math/cos %)} k)]
    (* (/ 1 n) (reduce + (map trig coll)))))

(defn mean-angle
  [degrees]
  (let [radians (map #(Math/toRadians %) degrees)
        a (mean-fn :sin radians)
        b (mean-fn :cos radians)]
    (Math/toDegrees (Math/atan2 a b))))


void setup() {
  float[] numbers = {3.1, 4.1, 5.9, 2.6, 5.3, 5.8};
  println(median(numbers));
  numbers = shorten(numbers);
  println(median(numbers));
}

float median(float[] nums) {
  nums = sort(nums);
  float median = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2.0;
  return median;
}


median(L, Z) :-
    length(L, Length),
    I is Length div 2,
    Rem is Length rem 2,
    msort(L, S),
    maplist(sumlist, [[I, Rem], [I, 1]], Mid),
    maplist(nth1, Mid, [S, S], X),
    sumlist(X, Y),
    Z is Y/2.


median x = (/(2-rem)) $ foldl1 (+) $ take (2-rem) $ drop (mid-(1-rem)) $ sort (<=) x
    when len = # x;
         mid = len div 2;
         rem = len mod 2;
         end;


Procedure.d median(Array values.d(1), length.i)
  If length = 0 : ProcedureReturn 0.0 : EndIf
  SortArray(values(), #PB_Sort_Ascending)
  If length % 2
    ProcedureReturn values(length / 2)
  EndIf
  ProcedureReturn 0.5 * (values(length / 2 - 1) + values(length / 2))
EndProcedure

Procedure.i readArray(Array values.d(1))
  Protected length.i, i.i
  Read.i length
  ReDim values(length - 1)
  For i = 0 To length - 1
    Read.d values(i)
  Next
  ProcedureReturn i
EndProcedure

Dim floats.d(0)
Restore array1
length.i = readArray(floats())
Debug median(floats(), length)
Restore array2
length.i = readArray(floats())
Debug median(floats(), length)

DataSection
  array1:
    Data.i 7
    Data.d 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2
  array2:
    Data.i 6
    Data.d 4.1, 7.2, 1.7, 9.3, 4.4, 3.2
EndDataSection


(defun average (list)
  (/ (reduce #'+ list) (length list)))

(defun radians (angle)
  (* pi 1/180 angle))

(defun degrees (angle)
  (* (/ 180 pi) angle))

(defun mean-angle (angles)
  (let* ((angles (map 'list #'radians angles))
	 (cosines (map 'list #'cos angles))
	 (sines (map 'list #'sin angles)))
    (degrees (atan (average sines) (average cosines)))))

(loop for angles in '((350 10) (90 180 270 360) (10 20 30))
   do (format t "~&The mean angle of ~a is ~$°." angles (mean-angle angles)))

;; or using complex numbers (cis and phase)

(defun mean-angle-2 (angles)
    (degrees (phase (reduce #'+ angles :key (lambda (deg) (cis (radians deg)))))))


import std.stdio, std.algorithm, std.complex;
import std.math: PI;

auto radians(T)(in T d) pure nothrow @nogc { return d * PI / 180; }
auto degrees(T)(in T r) pure nothrow @nogc { return r * 180 / PI; }

real meanAngle(T)(in T[] D) pure nothrow @nogc {
    immutable t = reduce!((a, d) => a + d.radians.expi)(0.complex, D);
    return (t / D.length).arg.degrees;
}

void main() {
    foreach (angles; [[350, 10], [90, 180, 270, 360], [10, 20, 30]])
        writefln("The mean angle of %s is: %.2f degrees",
                 angles, angles.meanAngle);
}


(define-syntax-rule  (deg->radian deg) (* deg 1/180 PI))
(define-syntax-rule  (radian->deg rad) (* 180 (/ PI) rad))

(define (mean-angles angles)
	(radian->deg
          (angle
	    (for/sum ((a angles)) (make-polar 1 (deg->radian a))))))

(mean-angles '( 350 10))
    → -0
(mean-angles '[90 180 270 360])
    → -90
(mean-angles '[10 20 30])
    → 20


#lang racket
(define (median numbers)
  (define sorted (list->vector (sort (vector->list numbers) <)))
  (define count (vector-length numbers))
  (if (zero? count)
      #f
      (/ (+ (vector-ref sorted (floor (/ (sub1 count) 2)))
            (vector-ref sorted (floor (/ count 2))))
         2)))

(median '#(5 3 4)) ;; 4
(median '#()) ;; #f
(median '#(5 4 2 3)) ;; 7/2
(median '#(3 4 1 -8.4 7.2 4 1 1.2)) ;; 2.1


sub median {
  my @a = sort @_;
  return (@a[(*-1) div 2] + @a[* div 2]) / 2;
}


median: func [
    "Returns the midpoint value in a series of numbers; half the values are above, half are below."
    block [any-block!]
    /local len mid
][
    if empty? block [return none]
    block: sort copy block
    len: length? block
    mid: to integer! len / 2
    either odd? len [
        pick block add 1 mid
    ][
        (block/:mid) + (pick block add 1 mid) / 2
    ]
]


let median = (arr) =>
{
    let float_compare = (a, b) => {
      let diff = a -. b
      if diff == 0.0 { 0 } else
      if diff > 0.0 { 1 } else { -1 }
    }
    let _ = Js.Array2.sortInPlaceWith(arr, float_compare)
    let count = Js.Array.length(arr)
    // find the middle value, or the lowest middle value
    let middleval = ((count - 1) / 2)
    let median =
      if (mod(count, 2) != 0) { // odd number, middle is the median
          arr[middleval]
      } else { // even number, calculate avg of 2 medians
          let low = arr[middleval]
          let high = arr[middleval+1]
          ((low +. high) /. 2.0)
      }
    median
}

Js.log(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]))
Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))


defmodule MeanAngle do
  def mean_angle(angles) do
    rad_angles = Enum.map(angles, &deg_to_rad/1)
    sines = rad_angles |> Enum.map(&:math.sin/1) |> Enum.sum
    cosines = rad_angles |> Enum.map(&:math.cos/1) |> Enum.sum

    rad_to_deg(:math.atan2(sines, cosines))
  end

  defp deg_to_rad(a) do
    (:math.pi/180) * a
  end

  defp rad_to_deg(a) do
    (180/:math.pi) * a
  end
end

IO.inspect MeanAngle.mean_angle([10, 350])
IO.inspect MeanAngle.mean_angle([90, 180, 270, 360])
IO.inspect MeanAngle.mean_angle([10, 20, 30])


-module( mean_angle ).
-export( [from_degrees/1, task/0] ).

from_degrees( Angles ) ->
	Radians = [radians(X) || X <- Angles],
	Sines = [math:sin(X) || X <- Radians],
	Coses = [math:cos(X) || X <- Radians],
	degrees( math:atan2( average(Sines), average(Coses) ) ).

task() ->
	Angles = [[350, 10], [90, 180, 270, 360], [10, 20, 30]],
	[io:fwrite( "Mean angle of ~p is: ~p~n", [X, erlang:round(from_degrees(X))] ) || X <- Angles].

average( List ) -> lists:sum( List ) / erlang:length( List ).

degrees( Radians ) -> Radians * 180 / math:pi().

radians( Degrees ) -> Degrees * math:pi() / 180.


/*REXX program finds the  median  of a  vector  (and displays the  vector  and  median).*/
/*  ══════════vector════════════   ══show vector═══   ════════show result═══════════    */
    v=  1 9 2 4                ;   say "vector"  v;   say 'median──────►' median(v);   say
    v=  3 1 4 1 5 9 7 6        ;   say "vector"  v;   say 'median──────►' median(v);   say
    v= '3 4 1 -8.4 7.2 4 1 1.2';   say "vector"  v;   say 'median──────►' median(v);   say
    v=  -1.2345678e99  2.3e700 ;   say "vector"  v;   say 'median──────►' median(v);   say
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSORT:  procedure expose @. #;     parse arg $;     #= words($)   /*$:  is the  vector. */
                do g=1  for #;   @.g= word($, g);   end  /*g*/    /*convert list──►array*/
        h=#                                                       /*#:  number elements.*/
                do  while  h>1;             h= h % 2              /*cut entries by half.*/
                   do i=1  for #-h;         j= i;        k= h + i /*sort lower section. */
                      do  while @.k<@.j;    parse value  @.j @.k  with  @.k @.j  /*swap.*/
                      if h>=j  then leave;  j= j - h;    k= k - h /*diminish  J  and  K.*/
                      end   /*while @.k<@.j*/
                   end      /*i*/
                end         /*while h>1*/                         /*end of exchange sort*/
        return
/*──────────────────────────────────────────────────────────────────────────────────────*/
median: procedure; call eSORT arg(1);   m= # % 2    /*   %   is REXX's integer division.*/
        n= m + 1                                    /*N:     the next element after  M. */
        if # // 2  then return @.n                  /*[odd?]   // ◄───REXX's ÷ remainder*/
                        return (@.m + @.n) / 2      /*process an  even─element  vector. */


aList = [5,4,2,3]
see "medium : " + median(aList) + nl

func median aray
     srtd = sort(aray)
     alen = len(srtd)
     if alen % 2 = 0
        return (srtd[alen/2] + srtd[alen/2 + 1]) / 2.0
     else return srtd[ceil(alen/2)] ok


def median(ary)
  return nil if ary.empty?
  mid, rem = ary.length.divmod(2)
  if rem == 0
    ary.sort[mid-1,2].inject(:+) / 2.0
  else
    ary.sort[mid]
  end
end

p median([])                        # => nil
p median([5,3,4])                   # => 4
p median([5,4,2,3])                 # => 3.5
p median([3,4,1,-8.4,7.2,4,1,1.2])  # => 2.1


>function meanangle (a) ...
$  z=sum(exp(rad(a)*I));
$  if z~=0 then error("Not meaningful");
$  else return deg(arg(z))
$  endfunction
>meanangle([350,10])
 0
>meanangle([90,180,270,360])
 Error : Not meaningful

 Error generated by error() command

 Error in function meanangle in line
 if z~=0 then error("Not meaningful");
>meanangle([10,20,30])
 20


include std/console.e
include std/mathcons.e

sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}}

function atan2(atom y, atom x)
	return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y)
end function

function MeanAngle(sequence angles)
	atom x = 0, y = 0
	integer l = length(angles)

	for i = 1 to length(angles) do
		x += cos(angles[i] * PI / 180)
		y += sin(angles[i] * PI / 180)
	end for

	return atan2(y / l, x / l) * 180 / PI
end function

for i = 1 to length(AngleList) do
	printf(1,"Mean Angle for set %d:  %3.5f\n",{i,MeanAngle(AngleList[i])})
end for

if getc(0) then end if


open System
open System.Numerics

let deg2rad d = d * Math.PI / 180.
let rad2deg r = r * 180. / Math.PI

[<EntryPoint>]
let main argv =
    let makeComplex = fun r ->  Complex.FromPolarCoordinates(1., r)
    argv
    |> Seq.map (Double.Parse >> deg2rad >> makeComplex)
    |> Seq.fold (fun x y -> Complex.Add(x,y)) Complex.Zero
    |> fun c -> c.Phase |> rad2deg
    |> printfn "Mean angle for [%s]: %g°" (String.Join("; ",argv))
    0


sqliteconnect #mem, ":memory:"
mem$ = "CREATE TABLE med (x float)"
#mem execute(mem$)

a$ ="4.1,5.6,7.2,1.7,9.3,4.4,3.2"	:gosub [median]
a$ ="4.1,7.2,1.7,9.3,4.4,3.2"		:gosub [median]
a$ ="4.1,4,1.2,6.235,7868.33"  		:gosub [median]
a$ ="1,5,3,2,4"       			:gosub [median]
a$ ="1,5,3,6,4,2"       		:gosub [median]
a$ ="4.4,2.3,-1.7,7.5,6.6,0.0,1.9,8.2,9.3,4.5"   :gosub [median]'
end
[median]
#mem execute("DELETE FROM med")
for i = 1 to 100
	v$	= word$( a$, i, ",")
	if v$ = "" then exit for
	mem$	= "INSERT INTO med values(";v$;")"
	#mem execute(mem$)
next i
mem$ = "SELECT AVG(x) as median FROM (SELECT x FROM med
ORDER BY x LIMIT 2 - (SELECT COUNT(*) FROM med) % 2
OFFSET (SELECT (COUNT(*) - 1) / 2
FROM med))"

#mem	execute(mem$)
	#row 	= #mem #nextrow()
	median	= #row median()
print " Median :";median;chr$(9);" Values:";a$

RETURN


fn median(mut xs: Vec<f64>) -> f64 {
    // sort in ascending order, panic on f64::NaN
    xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
    let n = xs.len();
    if n % 2 == 0 {
        (xs[n/2] + xs[n/2 - 1]) / 2.0
    } else {
        xs[n/2]
    }
}

fn main() {
    let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];
    println!("{:?}", median(nums))
}


def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
  import n._
  val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
  if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
}


(define (median l)
  (* (+ (list-ref (bubble-sort l >) (round (/ (- (length l) 1) 2)))
        (list-ref (bubble-sort l >) (round (/ (length l) 2)))) 0.5))


USING: formatting kernel math math.functions math.libm math.trig
sequences ;

: mean-angle ( seq -- x )
    [ deg>rad ] map [ [ sin ] map-sum ] [ [ cos ] map-sum ]
    [ length ] tri recip [ * ] curry [email protected] fatan2 rad>deg ;

: show ( seq -- )
    dup mean-angle "The mean angle of %u is: %f°\n" printf ;

{ { 350 10 } { 90 180 270 360 } { 10 20 30 } } [ show ] each


!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun  3 18:07:59
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!  -7.80250048E-06         350          10
!   90.0000000              90         180         270         360
!   19.9999962              10          20          30
!
!Compilation finished at Mon Jun  3 18:07:59

program average_angles
  !real(kind=8), parameter :: TAU = 6.283185307179586232 ! http://tauday.com/
  !integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/)
  !integer :: i, j, n
  !complex(kind=16) :: some
  !real(kind=8) :: angle
  real, parameter :: TAU = 6.283185307179586232 ! http://tauday.com/
  integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/)
  integer :: i, j, n
  complex :: some
  real :: angle
  i = 1
  n = int(test_data(i))
  do while (0 .lt. n)
    some = 0
    do j = 1, n
      angle = (TAU/360)*test_data(i+j)
      some = some + cmplx(cos(angle), sin(angle))
    end do
    some = some / n
    write(6,*)(360/TAU)*atan2(aimag(some), real(some)),test_data(i+1:i+n)
    i = i + n + 1
    n = int(test_data(i))
  end do
end program average_angles


$ include "seed7_05.s7i";
  include "float.s7i";

const type: floatList is array float;

const func float: median (in floatList: floats) is func
  result
    var float: median is 0.0;
  local
    var floatList: sortedFloats is 0 times 0.0;
  begin
    sortedFloats := sort(floats);
    if odd(length(sortedFloats)) then
      median := sortedFloats[succ(length(sortedFloats)) div 2];
    else
      median := 0.5 * (sortedFloats[length(sortedFloats) div 2] +
                       sortedFloats[succ(length(sortedFloats) div 2)]);
    end if;
  end func;

const proc: main is func
  local
    const floatList: flist1 is [] (5.1, 2.6, 6.2, 8.8, 4.6, 4.1);
    const floatList: flist2 is [] (5.1, 2.6, 8.8, 4.6, 4.1);
  begin
    writeln("flist1 median is " <& median(flist1) digits 2 lpad 7); # 4.85
    writeln("flist2 median is " <& median(flist2) digits 2 lpad 7); # 4.60
  end func;


put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
put the median of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]

put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
put customMedian of [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2, 6.6]

to handle customMedian of list
	sort list
	if the number of items in list is an even number then
		set lowMid to the number of items in list divided by 2
		return (item lowMid of list + item lowMid+1 of list) / 2
	else
		return the middle item of list
	end if
end customMedian


func median(arry) {
    var srtd = arry.sort;
    var alen = srtd.length;
    srtd[(alen-1)/2]+srtd[alen/2] / 2;
}


[email protected](Sequence traits) median
[
  s isEmpty
    ifTrue: [Nil]
    ifFalse:
      [| sorted |
       sorted: s sort.
       sorted length `cache isEven
         ifTrue: [(sorted middle + (sorted at: sorted indexMiddle - 1)) / 2]
         ifFalse: [sorted middle]]
].


' FB 1.05.0 Win64

Const PI As Double = 3.1415926535897932

Function MeanAngle(angles() As Double) As Double
  Dim As Integer length = Ubound(angles) - Lbound(angles) + 1
  Dim As Double sinSum = 0.0
  Dim As Double cosSum = 0.0
  For i As Integer = LBound(angles) To UBound(angles)
    sinSum += Sin(angles(i) * PI / 180.0)
    cosSum += Cos(angles(i) * PI / 180.0)
  Next
  Return Atan2(sinSum / length, cosSum / length) * 180.0 / PI
End Function

Dim As Double angles1(1 To 2) = {350, 10}
Dim As Double angles2(1 To 4) = {90, 180, 270, 360}
Dim As Double angles3(1 To 3) = {10, 20, 30}

Print Using "Mean for angles 1 is : ####.## degrees"; MeanAngle(angles1())
Print Using "Mean for angles 2 is : ####.## degrees"; MeanAngle(angles2())
Print Using "Mean for angles 3 is : ####.## degrees"; MeanAngle(angles3())
Print
Print "Press any key to quit the program"
Sleep


package main

import (
	"fmt"
	"math"
	"math/cmplx"
)

func deg2rad(d float64) float64 { return d * math.Pi / 180 }
func rad2deg(r float64) float64 { return r * 180 / math.Pi }

func mean_angle(deg []float64) float64 {
	sum := 0i
	for _, x := range deg {
		sum += cmplx.Rect(1, deg2rad(x))
	}
	return rad2deg(cmplx.Phase(sum))
}

func main() {
	for _, angles := range [][]float64{
		{350, 10},
		{90, 180, 270, 360},
		{10, 20, 30},
	} {
		fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles))
	}
}


OrderedCollection extend [
    median [
      self size = 0
        ifFalse: [ |s l|
          l := self size.
          s := self asSortedCollection.
	  (l rem: 2) = 0
	    ifTrue: [ ^ ((s at: (l//2 + 1)) + (s at: (l//2))) / 2 ]
	    ifFalse: [ ^ s at: (l//2 + 1) ]
	]
	ifTrue: [ ^nil ]
    ]
].


set obs 100000
gen x=rbeta(0.2,1.3)
quietly summarize x, detail
display r(p50)


proc median args {
    set list [lsort -real $args]
    set len [llength $list]
    # Odd number of elements
    if {$len & 1} {
        return [lindex $list [expr {($len-1)/2}]]
    }
    # Even number of elements
    set idx2 [expr {$len/2}]
    set idx1 [expr {$idx2-1}]
    return [expr {
        ([lindex $list $idx1] + [lindex $list $idx2])/2.0
    }]
}

puts [median 3.0 4.0 1.0 -8.4 7.2 4.0 1.0 1.2]; # --> 2.1


import static java.lang.Math.*
def meanAngle = {
    atan2( it.sum { sin(it * PI / 180) } / it.size(), it.sum { cos(it * PI / 180) } / it.size()) * 180 / PI
}


import Data.Complex (cis, phase)

meanAngle
  :: RealFloat c
  => [c] -> c
meanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi))

main :: IO ()
main =
  mapM_
    (\angles ->
        putStrLn $
        "The mean angle of " ++
        show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees")
    [[350, 10], [90, 180, 270, 360], [10, 20, 30]]


procedure main(A)
    write("Mean angle is ",meanAngle(A))
end

procedure meanAngle(A)
    every (sumSines := 0.0) +:= sin(dtor(!A))
    every (sumCosines := 0.0) +:= cos(dtor(!A))
    return rtod(atan(sumSines/*A,sumCosines/*A))
end


#import std
#import flo

median = fleq-<; @K30K31X eql?\~&rh div\2.+ [email protected]


int compare_numbers(void* a_ref, void* b_ref) {
    double a = *(double*) a_ref;
    double b = *(double*) b_ref;
    return a > b ? 1 : a < b ? -1 : 0;
}

double median(double[] elements) {
    double[] clone = elements;
    Posix.qsort(clone, clone.length, sizeof(double), compare_numbers);
    double middle = clone.length / 2.0;
    int first = (int) Math.floor(middle);
    int second = (int) Math.ceil(middle);
    return (clone[first] + clone[second]) / 2;
}
void main() {
    double[] array1 = {2, 4, 6, 1, 7, 3, 5};
    double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8};
    print(@"$(median(array1)) $(median(array2))\n");
}


function mean_angle, phi
        z = total(exp(complex(0,phi*!dtor)))
	return, atan(imaginary(z),real_part(z))*!radeg
end


import java.util.Arrays;

public class AverageMeanAngle {

    public static void main(String[] args) {
        printAverageAngle(350.0, 10.0);
        printAverageAngle(90.0, 180.0, 270.0, 360.0);
        printAverageAngle(10.0, 20.0, 30.0);
        printAverageAngle(370.0);
        printAverageAngle(180.0);
    }

    private static void printAverageAngle(double... sample) {
        double meanAngle = getMeanAngle(sample);
        System.out.printf("The mean angle of %s is %s%n", Arrays.toString(sample), meanAngle);
    }

    public static double getMeanAngle(double... anglesDeg) {
        double x = 0.0;
        double y = 0.0;

        for (double angleD : anglesDeg) {
            double angleR = Math.toRadians(angleD);
            x += Math.cos(angleR);
            y += Math.sin(angleR);
        }
        double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length);
        return Math.toDegrees(avgR);
    }
}


Private Function medianq(s As Variant) As Double
    Dim res As Double, tmp As Integer
    Dim l As Integer, k As Integer
    res = 0
    l = UBound(s): k = WorksheetFunction.Floor_Precise((l + 1) / 2, 1)
        If l Then
            res = quick_select(s, k)
            If l Mod 2 = 0 Then
                tmp = quick_select(s, k + 1)
                res = (res + tmp) / 2
            End If
        End If
    medianq = res
End Function
Public Sub main2()
    s = [{4, 2, 3, 5, 1, 6}]
    Debug.Print medianq(s)
End Sub


Sort(0, File_Size, NOCOLLATE+NORESTORE)
EOF Goto_Line(Cur_Line/2)
Reg_Copy(10, 1)


fn main() {
    println(median([3, 1, 4, 1]))    // prints 2
    println(median([3, 1, 4, 1, 5])) // prints 3
}

fn median(aa []int) int {
    mut a := aa.clone()
    a.sort()
    half := a.len / 2
    mut m := a[half]
    if a.len%2 == 0 {
        m = (m + a[half-1]) / 2
    }
    return m
}


function sum(a) {
    var s = 0;
    for (var i = 0; i < a.length; i++) s += a[i];
    return s;
}

function degToRad(a) {
    return Math.PI / 180 * a;
}

function meanAngleDeg(a) {
    return 180 / Math.PI * Math.atan2(
        sum(a.map(degToRad).map(Math.sin)) / a.length,
        sum(a.map(degToRad).map(Math.cos)) / a.length
    );
}

var a = [350, 10], b = [90, 180, 270, 360],  c = [10, 20, 30];
console.log(meanAngleDeg(a));
console.log(meanAngleDeg(b));
console.log(meanAngleDeg(c));


def pi: 4 * (1|atan);

def deg2rad: . * pi / 180;

def rad2deg: if . == null then null else . * 180 / pi end;

# Input: [x,y] (special handling of x==0)
# Output: [r, theta] where theta may be null
def to_polar:
  if .[0] == 0
  then [1, if .[1] > 5e-14 then pi/2 elif .[1] < -5e-14 then -pi/2 else null end]
  else [1, ((.[1]/.[0]) | atan)]
  end;

def from_polar: .[1] | [ cos, sin];

def abs: if . < 0 then - . else . end;

def summation(f): map(f) | add;


using Statistics
meandegrees(degrees) = rad2deg(atan(mean(sind.(degrees)), mean(cosd.(degrees))))


import "/sort" for Sort, Find
import "/math" for Nums
import "/queue" for PriorityQueue

var lists = [
    [5, 3, 4],
    [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]
]

for (l in lists) {
    // sort and then find median
    var l2 = Sort.merge(l)
    System.print(Nums.median(l2))

    // using a priority queue
    var pq = PriorityQueue.new()
    for (e in l) pq.push(e, -e)
    var c = pq.count
    var v = pq.values
    var m = (c % 2 == 1) ? v[(c/2).floor] : (v[c/2] + v[c/2-1])/2
    System.print(m)

    // using quickselect
    if (c % 2 == 1) {
        System.print(Find.quick(l, (c/2).floor))
    } else {
        var m1 = Find.quick(l, c/2-1)
        var m2 = Find.quick(l, c/2)
        System.print((m1 + m2)/2)
    }
    System.print()
}


sub floor(x)
    return int(x + .05)
end sub

sub ceil(x)
    if x > int(x) x = x + 1
    return x
end sub

SUB ASort$(matriz$())
    local last, gap, first, tempi$, tempj$, i, j

    last = arraysize(matriz$(), 1)

    gap = floor(last / 10) + 1
    while(TRUE)
	first = gap + 1
	for i = first to last
	    tempi$ = matriz$(i)
	    j = i - gap
	    while(TRUE)
	        tempj$ = matriz$(j)
	 	if (tempi$ >= tempj$) then
	   	    j = j + gap
	   	    break
	 	end if
	 	matriz$(j+gap) = tempj$
	 	if j <= gap then
	   	    break
	 	end if
	 	j = j - gap
	    wend
	    matriz$(j) = tempi$
        next i
	if gap = 1 then
	    return
	else
	    gap = floor(gap / 3.5) + 1
	end if
    wend
END SUB

sub median(numlist$)
    local numlist$(1), n

    n = token(numlist$, numlist$(), ", ")

    ASort$(numlist$())

    if mod(n, 2) = 0 then return (val(numlist$(n / 2)) + val(numlist$(n / 2 + 1))) / 2 end if
    return val(numlist$(ceil(n / 2)))
end sub

print median("4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2")    // 4.4
print median("4.1, 7.2, 1.7, 9.3, 4.4, 3.2")         // 4.25


var quickSelect=Import("quickSelect").qselect;

fcn median(xs){
   n:=xs.len();
   if (n.isOdd) return(quickSelect(xs,n/2));
   ( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2;
}


// version 1.0.5-2

fun meanAngle(angles: DoubleArray): Double {
    val sinSum = angles.sumByDouble {  Math.sin(it * Math.PI / 180.0) }
    val cosSum = angles.sumByDouble {  Math.cos(it * Math.PI / 180.0) }
    return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI
}

fun main(args: Array<String>) {
    val angles1 = doubleArrayOf(350.0, 10.0)
    val angles2 = doubleArrayOf(90.0, 180.0, 270.0, 360.0)
    val angles3 = doubleArrayOf(10.0, 20.0, 30.0)
    val fmt  = "%.2f degrees" // format results to 2 decimal places
    println("Mean for angles 1 is ${fmt.format(meanAngle(angles1))}")
    println("Mean for angles 2 is ${fmt.format(meanAngle(angles2))}")
    println("Mean for angles 3 is ${fmt.format(meanAngle(angles3))}")
}


global Pi
Pi =3.1415926535

print "Mean Angle( "; chr$( 34); "350,10"; chr$( 34); ") = ";         using( "###.#", meanAngle( "350,10")); " degrees."             '          0
print "Mean Angle( "; chr$( 34); "90,180,270,360"; chr$( 34); ") = "; using( "###.#", meanAngle( "90,180,270,360")); " degrees."  '        -90
print "Mean Angle( "; chr$( 34); "10,20,30"; chr$( 34); ") = ";       using( "###.#", meanAngle( "10,20,30")); " degrees."        '         20

end

function meanAngle( angles$)
   term =1
   while word$( angles$, term, ",") <>""
      angle  =val( word$( angles$, term, ","))
      sumSin = sumSin +sin( degRad( angle))
      sumCos = sumCos +cos( degRad( angle))
      term =term +1
   wend
   meanAngle= radDeg( atan2( sumSin, sumCos))
   if abs( sumSin) +abs( sumCos) <0.001 then notice "Not Available." +_
     chr$( 13) +"(" +angles$ +")" +_
     chr$( 13) +"Result nearly equals zero vector." +_
     chr$( 13) +"Displaying '666'.": meanAngle =666

end function

function degRad( theta)
    degRad =theta *Pi /180
end function

function radDeg( theta)
    radDeg =theta *180 /Pi
end function

function atan2( y, x)
    if x >0           then at =atn( y /x)
    if y >=0 and x <0 then at =atn( y /x) +pi
    if y <0  and x <0 then at =atn( y /x) -pi
    if y >0  and x =0 then at =    pi /2
    if y <0  and x =0 then at = 0 -pi /2
    if y =0  and x =0 then notice "undefined": end
    atan2 =at
end function


program: median
  case: 1
    input: [4,5,6,8,9]
    output: 6
  case: 2
    input: [2,5,6]
    output: 5
  case: 3
    input: [2,5,6,8]
    output: 5.5


module Averages;

type
	Vector = array {math} * of real;

procedure Partition(var a: Vector; left, right: integer): integer;
var
	pValue,aux: real;
	store,i,pivot: integer;
begin
	pivot := right;
	pValue := a[pivot];
	aux := a[right];a[right] := a[pivot];a[pivot] := aux; (* a[pivot] <-> a[right] *)
	store := left;
	for i := left to right -1 do
		if a[i] <= pValue then
			aux := a[store];a[store] := a[i];a[i]:=aux;
			inc(store)
		end
	end;
	aux := a[right];a[right] := a[store]; a[store] := aux;
	return store
end Partition;

(* QuickSelect algorithm *)
procedure Select(a: Vector; left,right,k: integer;var r: real);
var
	pIndex, pDist : integer;
begin
	if left = right then r := a[left]; return end;
	pIndex := Partition(a,left,right);
	pDist := pIndex - left + 1;
	if pDist = k then
		r := a[pIndex];return
	elsif k < pDist then
		Select(a,left, pIndex - 1, k, r)
	else
		Select(a,pIndex + 1, right, k - pDist, r)
	end
end Select;

procedure Median(a: Vector): real;
var
	idx: integer;
	r1,r2 : real;
begin
	idx := len(a) div 2 + 1;
	r1 := 0.0;r2 := 0.0;
	Select(a,0,len(a) - 1,idx,r1);
	if odd(len(a)) then return r1 end;
	Select(a,0,len(a) - 1,idx - 1,r2);
	return (r1 + r2) / 2;
end Median;

var
	ary: Vector;
	r: real;

begin
	ary := new Vector(3);
	ary := [5.0,3.0,4.0];
	writeln(Median(ary):10:2);
	ary := new Vector(4);
	ary := [5.0,4.0,2.0,3.0];
	writeln(Median(ary):10:2);
	ary := new Vector(8);
	ary := [3.0,4.0,1.0,-8.4,7.2,4.0,1.0,1.2];
	writeln(Median(ary):10:2)
end Averages.


to mean_angle :angles
   local "avgsin
   make "avgsin quotient apply "sum map "sin :angles count :angles
   local "avgcos
   make "avgcos quotient apply "sum map "cos :angles count :angles
   output (arctan :avgcos :avgsin)
end

foreach [[350 10] [90 180 270 360] [10 20 30]] [
  print (sentence [The average of \(] ? [\) is] (mean_angle ?))
]

bye


function meanAngle (angleList)
  local sumSin, sumCos = 0, 0
  for i, angle in pairs(angleList) do
    sumSin = sumSin + math.sin(math.rad(angle))
    sumCos = sumCos + math.cos(math.rad(angle))
  end
  local result = math.deg(math.atan2(sumSin, sumCos))
  return string.format("%.2f", result)
end

print(meanAngle({350, 10}))
print(meanAngle({90, 180, 270, 360}))
print(meanAngle({10, 20, 30}))


meanAngle[data_List] := [email protected][Mean[Exp[I data Degree]]]/Degree


function u = mean_angle(phi)
	u = angle(mean(exp(i*pi*phi/180)))*180/pi;
end


/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 80

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getMeanAngle(angles) private static binary
  x_component = double 0.0
  y_component = double 0.0
  aK = int angles.words()
  loop a_ = 1 to aK
    angle_d = double angles.word(a_)
    angle_r = double Math.toRadians(angle_d)
    x_component = x_component + Math.cos(angle_r)
    y_component = y_component + Math.sin(angle_r)
    end a_
  x_component = x_component / aK
  y_component = y_component / aK
  avg_r = Math.atan2(y_component, x_component)
  avg_d = Math.toDegrees(avg_r)
  return avg_d

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  angleSet = [ '350 10', '90 180 270 360', '10 20 30', '370', '180' ]
  loop angles over angleSet
    say 'The mean angle of' angles.space(1, ',') 'is:'
    say '  'getMeanAngle(angles).format(6, 6)
    say
    end angles
  return


import math, complex

proc meanAngle(deg: openArray[float]): float =
  var c: Complex[float]
  for d in deg:
    c += rect(1.0, degToRad(d))
  radToDeg(phase(c / float(deg.len)))

echo "The 1st mean angle is: ", meanAngle([350.0, 10.0]), " degrees"
echo "The 2nd mean angle is: ", meanAngle([90.0, 180.0, 270.0, 360.0]), " degrees"
echo "The 3rd mean angle is: ", meanAngle([10.0, 20.0, 30.0]), " degrees"


MODULE MeanAngle;
IMPORT
  M := LRealMath,
  Out;
CONST
  toRads = M.pi / 180;
  toDegs = 180 / M.pi;
VAR
  grades: ARRAY 64 OF LONGREAL;

PROCEDURE Mean(g: ARRAY OF LONGREAL): LONGREAL;
VAR
  i: INTEGER;
  sumSin, sumCos: LONGREAL;
BEGIN
  i := 0;sumSin := 0.0;sumCos := 0.0;
  WHILE g[i] # 0.0 DO
    sumSin := sumSin + M.sin(g[i] * toRads);
    sumCos := sumCos + M.cos(g[i] * toRads);
    INC(i)
  END;
  RETURN M.arctan2(sumSin / i,sumCos / i);
END Mean;

BEGIN
  grades[0] := 350.0;grades[1] := 10.0;
  Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
  grades[0] := 90.0;grades[1] := 180.0;grades[2] := 270.0;grades[3] := 360.0;
  Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
  grades[0] := 10.0;grades[1] := 20.0;grades[2] := 30.0;grades[3] := 0.0;
  Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
END MeanAngle.


let pi = 3.14159_26535_89793_23846_2643

let deg2rad d =
  d *. pi /. 180.0

let rad2deg r =
  r *. 180.0 /. pi

let mean_angle angles =
  let rad_angles = List.map deg2rad angles in
  let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 rad_angles
  and sum_cos = List.fold_left (fun sum a -> sum +. cos a) 0.0 rad_angles
  in
  rad2deg (atan2 sum_sin sum_cos)

let test angles =
  Printf.printf "The mean angle of [%s] is: %g degrees\n"
    (String.concat "; " (List.map (Printf.sprintf "%g") angles))
    (mean_angle angles)

let () =
  test [350.0; 10.0];
  test [90.0; 180.0; 270.0; 360.0];
  test [10.0; 20.0; 30.0];
;;


/*REXX program computes the  mean angle  (angles expressed in degrees). */
numeric digits 50                      /*use fifty digits of precision, */
       showDig=10                      /*··· but only display 10 digits.*/
xl = 350 10            ;      say showit(xl, meanAngleD(xl) )
xl = 90 180 270 360    ;      say showit(xl, meanAngleD(xl) )
xl = 10 20 30          ;      say showit(xl, meanAngleD(xl) )
exit                                   /*stick a fork in it, we're done.*/
/*----------------------------------MEANANGD subroutine-----------------*/
meanAngleD:  procedure;  parse arg xl;   numeric digits digits()+digits()%4
sum.=0
n=words(xl)
do j=1 to n
  sum.0sin+=rxCalcSin(word(xl,j))
  sum.0cos+=rxCalcCos(word(xl,j))
  End
If sum.0cos=0 Then
  Return sign(sum.0sin/n)*90
Else
  Return rxCalcArcTan((sum.0sin/n)/(sum.0cos/n))

showit: procedure expose showDig;  numeric digits showDig;  parse arg a,mA
        return left('angles='a,30)  'mean angle='  format(mA,,showDig,0)/1

::requires rxMath library;


program MeanAngle;
{$IFDEF DELPHI}
  {$APPTYPE CONSOLE}
{$ENDIF}
uses
  math;// sincos and atan2
type
  tAngles = array of double;

function MeanAngle(const a:tAngles;cnt:longInt):double;
// calculates mean angle.
// returns 0.0 if direction is not sure.
const
  eps = 1e-10;

var
  i : LongInt;
  s,c,
  Sumsin,SumCos : extended;
begin
  IF cnt = 0 then
  Begin
    MeanAngle := 0.0;
    EXIT;
  end;

  SumSin:= 0;
  SumCos:= 0;
  For i := Cnt-1 downto 0 do
  Begin
    sincos(DegToRad(a[i]),s,c);
    Sumsin := sumSin+s;
    SumCos := sumCos+c;
  end;
  s := SumSin/cnt;
  c := sumCos/cnt;
  IF c > eps then
    MeanAngle := RadToDeg(arctan2(s,c))
  else
    // Not meaningful
    MeanAngle := 0.0;
end;

Procedure OutMeanAngle(const a:tAngles;cnt:longInt);
var
  i : longInt;
Begin
  IF cnt > 0 then
  Begin
    write('The mean angle of [');
    For i := 0 to Cnt-2 do
      write(a[i]:0:2,',');
    write(a[Cnt-1]:0:2,'] => ');
    writeln(MeanAngle(a,cnt):0:16);
  end;
end;

var
  a:tAngles;
Begin
  setlength(a,4);

  a[0] := 350;a[1] := 10;
  OutMeanAngle(a,2);
  a[0] := 90;a[1] := 180;a[2] := 270;a[3] := 360;
  OutMeanAngle(a,4);
  a[0] := 10;a[1] := 20;a[2] := 30;
  OutMeanAngle(a,3);

  setlength(a,0);
end.


with javascript_semantics
function MeanAngle(sequence angles)
    atom x = 0, y = 0
    for i=1 to length(angles) do
        atom ai_rad = angles[i]*PI/180
        x += cos(ai_rad)
        y += sin(ai_rad)
    end for
    if abs(x)<1e-16 then return "not meaningful" end if
    return sprintf("%g",round(atan2(y,x)*180/PI,1e10))
end function

constant AngleLists = {{350,10},{90,180,270,360},{10,20,30},{180},{0,180}}
for i=1 to length(AngleLists) do
    sequence ai = AngleLists[i]
    printf(1,"%16V: Mean Angle is %s\n",{ai,MeanAngle(ai)})
end for


<?php
$samples = array(
	'1st' => array(350, 10),
	'2nd' => array(90, 180, 270, 360),
	'3rd' => array(10, 20, 30)
);

foreach($samples as $key => $sample){
	echo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL;
}

function meanAngle ($angles){
	$y_part = $x_part = 0;
	$size = count($angles);
	for ($i = 0; $i < $size; $i++){
		$x_part += cos(deg2rad($angles[$i]));
		$y_part += sin(deg2rad($angles[$i]));
	}
	$x_part /= $size;
	$y_part /= $size;
	return rad2deg(atan2($y_part, $x_part));
}
?>


averages: procedure options (main);             /* 31 August 2012 */
   declare b1(2) fixed initial (350, 10);
   declare b2(4) fixed initial (90, 180, 270, 360);
   declare b3(3) fixed initial (10, 20, 30);

   put edit ( b1) (f(7));
   put edit ( ' mean=', mean(b1) )   (a, f(7) );
   put skip edit ( b3) (f(7));
   put edit ( ' mean=', mean(b3) )   (a, f(7) );
   put skip edit ( b2) (f(7));
   put edit ( ' mean=', mean(b2) )   (a, f(7) );

mean: procedure (a) returns (fixed);
   declare a(*) float (18);
   return ( atand(sum(sind(a))/hbound(a), sum(cosd(a))/hbound(a) ) );
end mean;

end averages;


function Get-MeanAngle ([double[]]$Angles)
{
    $x = ($Angles | ForEach-Object {[Math]::Cos($_ * [Math]::PI / 180)} | Measure-Object -Average).Average
    $y = ($Angles | ForEach-Object {[Math]::Sin($_ * [Math]::PI / 180)} | Measure-Object -Average).Average

    [Math]::Atan2($y, $x) * 180 / [Math]::PI
}


void setup() {
  println(meanAngle(350, 10));
  println(meanAngle(90, 180, 270, 360));
  println(meanAngle(10, 20, 30));
}

float meanAngle(float... angles) {
  float sum1 = 0, sum2 = 0;
  for (int i = 0; i < angles.length; i++) {
    sum1 += sin(radians(angles[i])) / angles.length;
    sum2 += cos(radians(angles[i])) / angles.length;
  }
  return degrees(atan2(sum1, sum2));
}


NewList angle.d()

Macro AE(x)
  AddElement(angle()) : angle()=x
EndMacro

Procedure.d atan3(y.d,x.d)
  If x<=0.0 : ProcedureReturn Sign(y)*#PI/2 : EndIf
  If x>0.0  : ProcedureReturn ATan(y/x)     : EndIf
  If y>0.0  : ProcedureReturn ATan(y/x)+#PI : EndIf
  ProcedureReturn ATan(y/x)-#PI
EndProcedure

Procedure.d mAngle(List angle.d())
  Define.d sumS,sumC
  ForEach angle()
    sumS+Sin(Radian(angle())) : sumC+Cos(Radian(angle()))
  Next
  ProcedureReturn Degree(atan3(sumS,sumC))
EndProcedure

AE(350.0) : AE(10.0)
Debug StrD(mAngle(angle()),6) : ClearList(angle())

AE(90.0) : AE(180.0) : AE(270.0) : AE(360.0)
Debug StrD(mAngle(angle()),6) : ClearList(angle())

AE(10.0) : AE(20.0) : AE(30.0)
Debug StrD(mAngle(angle()),6) : ClearList(angle())


>>> from cmath import rect, phase
>>> from math import radians, degrees
>>> def mean_angle(deg):
...     return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))
...
>>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:
...     print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')
...
The mean angle of [350, 10] is: -0.0 degrees
The mean angle of [90, 180, 270, 360] is: -90.0 degrees
The mean angle of [10, 20, 30] is: 20.0 degrees
>>>


deg2rad <- function(x) {
  x * pi/180
}

rad2deg <- function(x) {
  x * 180/pi
}

deg2vec <- function(x) {
  c(sin(deg2rad(x)), cos(deg2rad(x)))
}

vec2deg <- function(x) {
  res <- rad2deg(atan2(x[1], x[2]))
  if (res < 0) {
    360 + res
  } else {
    res
  }
}

mean_vec <- function(x) {
  y <- lapply(x, deg2vec)
  Reduce(`+`, y)/length(y)
}

mean_deg <- function(x) {
  vec2deg(mean_vec(x))
}

mean_deg(c(350, 10))
mean_deg(c(90, 180, 270, 360))
mean_deg(c(10, 20, 30))


#lang racket

(define (mean-angle αs)
  (radians->degrees
   (mean-angle/radians
    (map degrees->radians αs))))

(define (mean-angle/radians αs)
  (define n (length αs))
  (atan (* (/ 1 n) (for/sum ([α_j αs]) (sin α_j)))
        (* (/ 1 n) (for/sum ([α_j αs]) (cos α_j)))))

(mean-angle '(350 0 10))
(mean-angle '(90 180 270 360))
(mean-angle '(10 20 30))


# Of course, you can still use pi and 180.
sub deg2rad { $^d * tau / 360 }
sub rad2deg { $^r * 360 / tau }

sub phase ($c)  {
    my ($mag,$ang) = $c.polar;
    return NaN if $mag < 1e-16;
    $ang;
}

sub meanAngle { rad2deg phase [+] map { cis deg2rad $_ }, @^angles }

say meanAngle($_).fmt("%.2f\tis the mean angle of "), $_ for
    [350, 10],
    [90, 180, 270, 360],
    [10, 20, 30];


Note that the second set of angles:    90    180   270   360

is the same as:                        90    180   -90     0
           and:                      -270   -180   -90  -360

and other combinations.


# Project : Averages/Mean angle

load "stdlib.ring"
decimals(6)
pi = 3.1415926535897
angles = [350,10]
see meanangle(angles, len(angles)) + nl
angles = [90,180,270,360]
see meanangle(angles, len(angles)) + nl
angles = [10,20,30]
see meanangle(angles, len(angles)) + nl

func meanangle(angles, n)
        sumsin = 0
        sumcos = 0
        for i = 1 to n
             sumsin = sumsin + sin(angles[i]*pi/180)
             sumcos = sumcos + cos(angles[i]*pi/180)
        next
        return 180/pi*atan3(sumsin, sumcos)

func atan3(y,x)
        if x <= 0
           return sign(y)*pi/2
        ok
        if x>0
           return atan(y/x)
        else
           if y>0
              return atan(y/x)+pi
           else
              return atan(y/x)-pi
           ok
        ok


require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.

def deg2rad(d)
  d * Math::PI / 180
end

def rad2deg(r)
  r * 180 / Math::PI
end

def mean_angle(deg)
  rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg)
end

[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles|
  puts "The mean angle of %p is: %f degrees" % [angles, mean_angle(angles)]
}


use std::f64;
// the macro is from
// http://stackoverflow.com/questions/30856285/assert-eq-with-floating-
// point-numbers-and-delta
fn mean_angle(angles: &[f64]) -> f64 {
    let length: f64 = angles.len() as f64;
    let cos_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().cos()) / length;
    let sin_mean: f64 = angles.iter().fold(0.0, |sum, i| sum + i.to_radians().sin()) / length;
    (sin_mean).atan2(cos_mean).to_degrees()
}

fn main() {
    let angles1 = [350.0_f64, 10.0];
    let angles2 = [90.0_f64, 180.0, 270.0, 360.0];
    let angles3 = [10.0_f64, 20.0, 30.0];
    println!("Mean Angle for {:?}  is {:.5} degrees",
             &angles1,
             mean_angle(&angles1));
    println!("Mean Angle for {:?}  is {:.5} degrees",
             &angles2,
             mean_angle(&angles2));
    println!("Mean Angle for {:?}  is {:.5} degrees",
             &angles3,
             mean_angle(&angles3));
}

macro_rules! assert_diff{
    ($x: expr,$y : expr, $diff :expr)=>{
        if ( $x - $y ).abs() > $diff {
            panic!("floating point difference is to big {}", $x - $y );
        }
    }
}

#[test]
fn calculate() {
    let angles1 = [350.0_f64, 10.0];
    let angles2 = [90.0_f64, 180.0, 270.0, 360.0];
    let angles3 = [10.0_f64, 20.0, 30.0];
    assert_diff!(0.0, mean_angle(&angles1), 0.001);
    assert_diff!(-90.0, mean_angle(&angles2), 0.001);
    assert_diff!(20.0, mean_angle(&angles3), 0.001);
}


trait MeanAnglesComputation {
  import scala.math.{Pi, atan2, cos, sin}

  def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = {
    val sums = angles.foldLeft((.0, .0))((r, c) => {
      val rads = c / convFactor
      (r._1 + sin(rads), r._2 + cos(rads))
    })
    val result = atan2(sums._1, sums._2)
    (result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor
  }
}

object MeanAngles extends App with MeanAnglesComputation {
  assert(meanAngle(List(350, 10), 180.0 / math.Pi).round == 360, "Unexpected result with 350, 10")
  assert(meanAngle(List(90, 180, 270, 360)).round == 270, "Unexpected result with 90, 180, 270, 360")
  assert(meanAngle(List(10, 20, 30)).round == 20, "Unexpected result with 10, 20, 30")
  println("Successfully completed without errors.")
}


(import (srfi 1 lists))  ;; use 'fold' from library

(define (average l)
  (/ (fold + 0 l) (length l)))

(define pi 3.14159265358979323846264338327950288419716939937510582097)

(define (radians a)
  (* pi 1/180 a))

(define (degrees a)
  (* 180 (/ 1 pi) a))

(define (mean-angle angles)
  (let* ((angles (map radians angles))
         (cosines (map cos angles))
         (sines (map sin angles)))
    (degrees (atan (average sines) (average cosines)))))

(for-each (lambda (angles)
            (display "The mean angle of ") (display angles)
            (display " is ") (display (mean-angle angles)) (newline))
          '((350 10) (90 180 270 360) (10 20 30)))


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";
  include "complex.s7i";

const func float: deg2rad (in float: degree) is
  return degree * PI / 180.0;

const func float: rad2deg (in float: rad) is
  return rad * 180.0 / PI;

const func float: meanAngle (in array float: degrees) is func
  result
    var float: mean is 0.0;
  local
    var float: degree is 0.0;
    var complex: sum is complex.value;
  begin
    for degree range degrees do
      sum +:= polar(1.0, deg2rad(degree));
    end for;
    mean := rad2deg(arg(sum / complex conv length(degrees)));
  end func;

const proc: main is func
  begin
    writeln(meanAngle([] (350.0, 10.0)) digits 4);
    writeln(meanAngle([] (90.0, 180.0, 270.0, 360.0)) digits 4);
    writeln(meanAngle([] (10.0, 20.0, 30.0)) digits 4);
  end func;


func mean_angle(angles) {
    atan2(
        Math.avg(angles.map{ .deg2rad.sin }...),
        Math.avg(angles.map{ .deg2rad.cos }...),
    ) -> rad2deg
}

[[350,10], [90,180,270,360], [10,20,30]].each { |angles|
  say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees"
}


mata
function meanangle(a) {
	return(arg(sum(exp(C(0,a)))))
}

deg=pi()/180

meanangle((350,10)*deg)/deg
  -1.61481e-15
meanangle((90,180,270,360)*deg)/deg
  0
meanangle((10,20,30)*deg)/deg
  20
end


import Foundation

@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
@inlinable public func r2d<T: FloatingPoint>(_ f: T) -> T { f * 180 / .pi }

public func meanOfAngles(_ angles: [Double]) -> Double {
  let cInv = 1 / Double(angles.count)
  let (s, c) =
    angles.lazy
      .map(d2r)
      .map({ (sin($0), cos($0)) })
      .reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 })

  return r2d(atan2(cInv * s, cInv * c))
}

let fmt = { String(format: "%lf", $0) }

print("Mean of angles (350, 10) => \(fmt(meanOfAngles([350, 10])))")
print("Mean of angles (90, 180, 270, 360) => \(fmt(meanOfAngles([90, 180, 270, 360])))")
print("Mean of angles (10, 20, 30) => \(fmt(meanOfAngles([10, 20, 30])))")


proc meanAngle {angles} {
    set toRadians [expr {atan2(0,-1) / 180}]
    set sumSin [set sumCos 0.0]
    foreach a $angles {
	set sumSin [expr {$sumSin + sin($a * $toRadians)}]
	set sumCos [expr {$sumCos + cos($a * $toRadians)}]
    }
    # Don't need to divide by counts; atan2() cancels that out
    return [expr {atan2($sumSin, $sumCos) / $toRadians}]
}


double meanAngle(double[] angles) {
  double y_part = 0.0;
  double x_part = 0.0;

  for (int i = 0; i < angles.length; i++) {
    x_part += Math.cos(angles[i] * Math.PI / 180.0);
    y_part += Math.sin(angles[i] * Math.PI / 180.0);
  }

  return Math.atan2(y_part / angles.length, x_part / angles.length) * 180 / Math.PI;
}

void main() {
  double[] angleSet1 = {350.0, 10.0};
  double[] angleSet2 = {90.0, 180.0, 270.0, 360.0};
  double[] angleSet3 = {10.0, 20.0, 30.0};

  print("\nMean Angle for 1st set :  %lf degrees", meanAngle(angleSet1));
  print("\nMean Angle for 2nd set : %lf degrees", meanAngle(angleSet2));
  print("\nMean Angle for 3rd set :  %lf degrees\n", meanAngle(angleSet3));
}


Option Base 1
Private Function mean_angle(angles As Variant) As Double
    Dim sins() As Double, coss() As Double
    ReDim sins(UBound(angles))
    ReDim coss(UBound(angles))
    For i = LBound(angles) To UBound(angles)
        sins(i) = Sin(WorksheetFunction.Radians(angles(i)))
        coss(i) = Cos(WorksheetFunction.Radians(angles(i)))
    Next i
    mean_angle = WorksheetFunction.Degrees( _
        WorksheetFunction.Atan2( _
        WorksheetFunction.sum(coss), _
        WorksheetFunction.sum(sins)))
End Function
Public Sub main()
    Debug.Print Format(mean_angle([{350,10}]), "##0")
    Debug.Print Format(mean_angle([{90, 180, 270, 360}]), "##0")
    Debug.Print Format(mean_angle([{10, 20, 30}]), "##0")
End Sub


Imports System.Math

Module Module1

    Function MeanAngle(angles As Double()) As Double
        Dim x = angles.Sum(Function(a) Cos(a * PI / 180)) / angles.Length
        Dim y = angles.Sum(Function(a) Sin(a * PI / 180)) / angles.Length
        Return Atan2(y, x) * 180 / PI
    End Function

    Sub Main()
        Dim printMean = Sub(x As Double()) Console.WriteLine("{0:0.###}", MeanAngle(x))
        printMean({350, 10})
        printMean({90, 180, 270, 360})
        printMean({10, 20, 30})
    End Sub

End Module


import math

fn mean_angle(deg []f64) f64 {
	mut ss, mut sc := f64(0), f64(0)
	for x in deg {
		s, c := math.sincos(x * math.pi / 180)
		ss += s
		sc += c
	}
	return math.atan2(ss, sc) * 180 / math.pi
}

fn main() {
	for angles in [
		[f64(350), 10],
		[f64(90), 180, 270, 360],
		[f64(10), 20, 30],
	] {
		println("The mean angle of $angles is: ${mean_angle(angles)} degrees")
	}
}


import "/fmt" for Fmt

var meanAngle = Fn.new { |angles|
    var n = angles.count
    var sinSum = 0
    var cosSum = 0
    for (angle in angles) {
        sinSum = sinSum + (angle * Num.pi / 180).sin
        cosSum = cosSum + (angle * Num.pi / 180).cos
    }
    return (sinSum/n).atan(cosSum/n) * 180 / Num.pi
}

var angles1 = [350, 10]
var angles2 = [90, 180, 270, 360]
var angles3 = [10, 20, 30]

var i = 1
for (angles in [angles1, angles2, angles3]) {
    System.print("Mean for angles %(i) is : %(Fmt.f(6, meanAngle.call(angles), 2))")
    i = i + 1
}


include c:\cxpl\codes;

def Pi  = 3.14159265358979323846;
def D2R = Pi/180.0;             \coefficient to convert degrees to radians

func real MeanAng(A);           \Return the mean of the given list of angles
int  A;
real X, Y;
int  I;
[X:= 0.0;  Y:= 0.0;
for I:= 1 to A(0) do
    [X:= X + Cos(D2R*float(A(I)));
     Y:= Y + Sin(D2R*float(A(I)));
    ];
return ATan2(Y,X)/D2R;
];

[Format(5, 15);
RlOut(0, MeanAng([2, 350, 10]));  CrLf(0);
RlOut(0, MeanAng([4, 90, 180, 270, 360]));  CrLf(0);
RlOut(0, MeanAng([3, 10, 20, 30]));  CrLf(0);
]


fcn meanA(a1,a2,etc){
   as:=vm.arglist.pump(List,"toFloat","toRad");
   n:=as.len();
   (as.apply("sin").sum(0.0)/n)
   .atan2(as.apply("cos").sum(0.0)/n)
   .toDeg()
}