Averages/Mean angle: Difference between revisions

m
(→‎{{header|Nim}}: Update code to work with newer versions, remove reimplementations of stdlib functions)
m (→‎{{header|Wren}}: Minor tidy)
 
(8 intermediate revisions by 7 users not shown)
Line 1:
[[Category:Geometry]]
{{task}}
 
Line 19 ⟶ 20:
::<math>\bar{\alpha} = \operatorname{atan2}\left(\frac{1}{n}\cdot\sum_{j=1}^n \sin\alpha_j, \frac{1}{n}\cdot\sum_{j=1}^n \cos\alpha_j\right) </math>
 
;Task
{{task heading}}
 
# write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. <br> (You should use a built-in function if you have one that does this for degrees or radians).
Line 36 ⟶ 37:
=={{header|11l}}==
{{trans|C#}}
<langsyntaxhighlight lang="11l">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
Line 43 ⟶ 44:
print(mean_angle([350, 10]))
print(mean_angle([90, 180, 270, 360]))
print(mean_angle([10, 20, 30]))</langsyntaxhighlight>
{{out}}
<pre>
Line 53 ⟶ 54:
=={{header|Ada}}==
An implementation based on the formula using the "Arctan" (atan2) function, thus avoiding complex numbers:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
 
procedure Mean_Angles is
Line 86 ⟶ 87:
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;</langsyntaxhighlight>
{{out}}
<pre> 20.00
Line 94 ⟶ 95:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">real
mean(list l)
{
Line 120 ⟶ 121:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>mean of 1st set: -.000000
Line 131 ⟶ 132:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{trans|C|Note: This specimen retains the original [[#C|C]] coding style}}
'''File: Averages_Mean_angle.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 156 ⟶ 157:
printf ((summary fmt,"2nd", mean angle (angle set 2)));
printf ((summary fmt,"3rd", mean angle (angle set 3)))
)</langsyntaxhighlight>{{out}}
<pre>
Mean angle for 1st set : -0.00000 degrees
Line 165 ⟶ 166:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Angles := [[350, 10], [90, 180, 270, 360], [10, 20, 30]]
MsgBox, % MeanAngle(Angles[1]) "`n"
. MeanAngle(Angles[2]) "`n"
Line 181 ⟶ 182:
atan2(x, y) {
return dllcall("msvcrt\atan2", "Double",y, "Double",x, "CDECL Double")
}</langsyntaxhighlight>
'''Output:'''
<pre>-0.000000
Line 188 ⟶ 189:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
{
PI = atan2(0,-1);
Line 200 ⟶ 201:
if (p<0) p += 360;
print p;
}</langsyntaxhighlight>
<pre> echo 350 10 | ./mean_angle.awk
360
Line 210 ⟶ 211:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
DIM angles(3)
angles() = 350,10
Line 229 ⟶ 230:
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</langsyntaxhighlight>
{{out}}
<pre>
Line 238 ⟶ 239:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include<math.h>
#include<stdio.h>
 
Line 267 ⟶ 268:
printf ("\nMean Angle for 3rd set : %lf degrees\n", meanAngle (angleSet3, 3));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Mean Angle for 1st set : -0.000000 degrees
Line 274 ⟶ 275:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using static System.Math;
Line 292 ⟶ 293:
printMean(new double[] { 10, 20, 30 });
}
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 300 ⟶ 301:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <vector>
Line 336 ⟶ 337:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>-0.000
Line 343 ⟶ 344:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn mean-fn
[k coll]
(let [n (count coll)
Line 354 ⟶ 355:
a (mean-fn :sin radians)
b (mean-fn :cos radians)]
(Math/toDegrees (Math/atan2 a b))))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="clojure">(mean-angle [350 10])
;=> -1.614809932057922E-15
 
Line 363 ⟶ 364:
 
(mean-angle [10 20 30])
;=> 19.999999999999996</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun average (list)
(/ (reduce #'+ list) (length list)))
 
Line 388 ⟶ 389:
(defun mean-angle-2 (angles)
(degrees (phase (reduce #'+ angles :key (lambda (deg) (cis (radians deg)))))))
</syntaxhighlight>
</lang>
{{out}}
<pre>The mean angle of (350 10) is -0.00°.
Line 395 ⟶ 396:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.complex;
import std.math: PI;
 
Line 410 ⟶ 411:
writefln("The mean angle of %s is: %.2f degrees",
angles, angles.meanAngle);
}</langsyntaxhighlight>
{{out}}
<pre>The mean angle of [350, 10] is: -0.00 degrees
Line 417 ⟶ 418:
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight lang=easylang>
func mean ang[] .
for ang in ang[]
x += cos ang
y += sin ang
.
return atan2 (y / len ang[]) (x / len ang[])
.
print mean [ 350 10 ]
print mean [ 90 180 270 360 ]
print mean [ 10 20 30 ]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define-syntax-rule (deg->radian deg) (* deg 1/180 PI))
(define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))
Line 433 ⟶ 449:
(mean-angles '[10 20 30])
→ 20
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule MeanAngle do
def mean_angle(angles) do
Line 458 ⟶ 474:
IO.inspect MeanAngle.mean_angle([90, 180, 270, 360])
IO.inspect MeanAngle.mean_angle([10, 20, 30])
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 468 ⟶ 484:
=={{header|Erlang}}==
The function from_degrees/1 is used to solve [[Averages/Mean_time_of_day]]. Please keep backwards compatibility when editing. Or update the other module, too.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( mean_angle ).
-export( [from_degrees/1, task/0] ).
Line 488 ⟶ 504:
 
radians( Degrees ) -> Degrees * math:pi() / 180.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 498 ⟶ 514:
 
=={{header|Euler Math Toolbox}}==
<langsyntaxhighlight EulerMathToolboxlang="eulermathtoolbox">>function meanangle (a) ...
$ z=sum(exp(rad(a)*I));
$ if z~=0 then error("Not meaningful");
Line 513 ⟶ 529:
if z~=0 then error("Not meaningful");
>meanangle([10,20,30])
20</langsyntaxhighlight>
 
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/console.e
include std/mathcons.e
Line 544 ⟶ 560:
 
if getc(0) then end if
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 553 ⟶ 569:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.Numerics
 
Line 567 ⟶ 583:
|> fun c -> c.Phase |> rad2deg
|> printfn "Mean angle for [%s]: %g°" (String.Join("; ",argv))
0</langsyntaxhighlight>
{{out}}
<pre>>RosettaCode 350 10
Line 580 ⟶ 596:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.functions math.libm math.trig
sequences ;
 
Line 590 ⟶ 606:
dup mean-angle "The mean angle of %u is: %f°\n" printf ;
 
{ { 350 10 } { 90 180 270 360 } { 10 20 30 } } [ show ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 600 ⟶ 616:
=={{header|Fortran}}==
Please find the example output along with the build instructions in the comments at the start of the FORTRAN 2008 source. Compiler: gfortran from the GNU compiler collection. Command interpreter: bash.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 18:07:59
Line 637 ⟶ 653:
end do
end program average_angles
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
 
Line 666 ⟶ 682:
Print "Press any key to quit the program"
Sleep
</syntaxhighlight>
</lang>
 
{{out}}
Line 677 ⟶ 693:
=={{header|Go}}==
===Complex===
<langsyntaxhighlight lang="go">package main
 
import (
Line 704 ⟶ 720:
fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 714 ⟶ 730:
A mean_angle function that could be substituted above. Functions deg2rad and rad2deg are not used here but there is no runtime advantage either way to using them or not. Inlining should result in eqivalent code being generated. Also the Go Atan2 library function has no limits on the arguments so there is no need to divide by the number of elements.
 
<langsyntaxhighlight lang="go">func mean_angle(deg []float64) float64 {
var ss, sc float64
for _, x := range deg {
Line 722 ⟶ 738:
}
return math.Atan2(ss, sc) * 180 / math.Pi
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">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
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def verifyAngle = { angles ->
def ma = meanAngle(angles)
printf("Mean Angle for $angles: %5.2f%n", ma)
Line 737 ⟶ 753:
assert verifyAngle([350, 10]) == -0
assert verifyAngle([90, 180, 270, 360]) == -90
assert verifyAngle([10, 20, 30]) == 20</langsyntaxhighlight>
{{out}}
<pre>Mean Angle for [350, 10]: -0.00
Line 744 ⟶ 760:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Complex (cis, phase)
 
meanAngle
Line 758 ⟶ 774:
"The mean angle of " ++
show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees")
[[350, 10], [90, 180, 270, 360], [10, 20, 30]]</langsyntaxhighlight>
{{out}}
<pre>
Line 769 ⟶ 785:
Alternative Solution: This solution gives an insight about using factoring, many small functions like Forth and using function composition.
 
<langsyntaxhighlight lang="haskell">
 
-- file: trigdeg.fs
Line 788 ⟶ 804:
 
-- End of trigdeg.fs --------
</syntaxhighlight>
</lang>
 
{{out}}
Line 811 ⟶ 827:
=={{header|Icon}} and {{header|Unicon}}==
 
<langsyntaxhighlight lang="unicon">procedure main(A)
write("Mean angle is ",meanAngle(A))
end
Line 819 ⟶ 835:
every (sumCosines := 0.0) +:= cos(dtor(!A))
return rtod(atan(sumSines/*A,sumCosines/*A))
end</langsyntaxhighlight>
 
Sample runs:
Line 832 ⟶ 848:
 
=={{header|IDL}}==
<langsyntaxhighlight IDLlang="idl">function mean_angle, phi
z = total(exp(complex(0,phi*!dtor)))
return, atan(imaginary(z),real_part(z))*!radeg
end</langsyntaxhighlight>
 
{{out}}
Line 847 ⟶ 863:
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j">avgAngleD=: 360|(_1 { [: (**|)&.+.@(+/ % #)&.(*.inv) 1,.])&.(1r180p1&*)</langsyntaxhighlight>
This verb can be represented as simpler component verbs, for example:
<langsyntaxhighlight Jlang="j">rfd=: 1r180p1&* NB. convert angle to radians from degrees
toComplex=: *.inv NB. maps integer pairs as length, complex angle (in radians)
mean=: +/ % # NB. calculate arithmetic mean
roundComplex=: (* * |)&.+. NB. discard an extraneous least significant bit of precision from a complex value whose magnitude is in the vicinity of 1
avgAngleR=: _1 { [: roundComplex@mean&.toComplex 1 ,. ] NB. calculate average angle in radians
avgAngleD=: 360|avgAngleR&.rfd NB. calculate average angle in degrees</langsyntaxhighlight>
Example use:
<langsyntaxhighlight Jlang="j"> avgAngleD 10 350
0
avgAngleD 90 180 270 360 NB. result not meaningful
Line 865 ⟶ 881:
5
avgAngleD 10 340
355</langsyntaxhighlight>
 
Notes:
Line 886 ⟶ 902:
{{trans|NetRexx}}
{{works with|Java|7+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class AverageMeanAngle {
Line 915 ⟶ 931:
return Math.toDegrees(avgR);
}
}</langsyntaxhighlight>
{{out}}
<pre>The mean angle of [350.0, 10.0] is -1.614809932057922E-15
Line 925 ⟶ 941:
=={{header|JavaScript}}==
===atan2===
<langsyntaxhighlight lang="javascript">function sum(a) {
var s = 0;
for (var i = 0; i < a.length; i++) s += a[i];
Line 945 ⟶ 961:
console.log(meanAngleDeg(a));
console.log(meanAngleDeg(b));
console.log(meanAngleDeg(c));</langsyntaxhighlight>
{{out}}
<pre>-1.614809932057922e-15
Line 958 ⟶ 974:
 
'''Generic Infrastructure'''
<langsyntaxhighlight lang="jq">def pi: 4 * (1|atan);
 
def deg2rad: . * pi / 180;
Line 976 ⟶ 992:
def abs: if . < 0 then - . else . end;
def summation(f): map(f) | add;</langsyntaxhighlight>
 
'''Mean Angle'''
<langsyntaxhighlight lang="jq"># input: degrees
def mean_angle:
def round:
Line 993 ⟶ 1,009:
| .[1]
| rad2deg
| round;</langsyntaxhighlight>
'''Examples'''
<langsyntaxhighlight lang="jq">([350, 10], [90, 180, 270, 360], [10, 20, 30])
| "The mean angle of \(.) is: \(mean_angle)"</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="sh">jq -r -n -f Mean_angle.jq
The mean angle of [350,10] is: 0
The mean angle of [90,180,270,360] is: null
The mean angle of [10,20,30] is: 20</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia has built-in functions <code>sind</code> and <code>cosd</code> to compute the sine and cosine of angles specified in degrees accurately (avoiding the roundoff errors incurred in conversion to radians), and a built-in function to convert radians to degrees (or vice versa). Using these:
<langsyntaxhighlight lang="julia">using Statistics
meandegrees(degrees) = rad2deg(atan(mean(sind.(degrees)), mean(cosd.(degrees))))</langsyntaxhighlight>
The output is:
<langsyntaxhighlight lang="julia">julia> meandegrees([350, 10])
0.0
 
Line 1,016 ⟶ 1,032:
 
julia> meandegrees([10, 20, 30]])
19.999999999999996</langsyntaxhighlight>
(Note that the mean of 90°, 180°, 270°, and 360° gives zero because of the lack of roundoff errors in the <code>sind</code> function, since the standard-library <code>atan2(0,0)</code> value is zero. Many of the other languages report an average of 90° or –90° in this case due to rounding errors.)
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun meanAngle(angles: DoubleArray): Double {
Line 1,036 ⟶ 1,052:
println("Mean for angles 2 is ${fmt.format(meanAngle(angles2))}")
println("Mean for angles 3 is ${fmt.format(meanAngle(angles3))}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,046 ⟶ 1,062:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">global Pi
Pi =3.1415926535
 
Line 1,087 ⟶ 1,103:
if y =0 and x =0 then notice "undefined": end
atan2 =at
end function</langsyntaxhighlight>
{{out}}
<pre>
Line 1,096 ⟶ 1,112:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to mean_angle :angles
local "avgsin
make "avgsin quotient apply "sum map "sin :angles count :angles
Line 1,109 ⟶ 1,125:
 
bye
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,119 ⟶ 1,135:
{{trans|Tcl}}
{{works with|Lua|5.1}}
<langsyntaxhighlight Lualang="lua">function meanAngle (angleList)
local sumSin, sumCos = 0, 0
for i, angle in pairs(angleList) do
Line 1,131 ⟶ 1,147:
print(meanAngle({350, 10}))
print(meanAngle({90, 180, 270, 360}))
print(meanAngle({10, 20, 30}))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,141 ⟶ 1,157:
=={{header|Maple}}==
The following procedure takes a list of numeric degrees (with attached units) such as
<langsyntaxhighlight Maplelang="maple">> [ 350, 10 ] *~ Unit(arcdeg);
[350 [arcdeg], 10 [arcdeg]]</langsyntaxhighlight>
as input. (We could use "degree" instead of "arcdeg", since "degree" is taken, by default, to mean angle measure, but it seems best to avoid the ambiguity.)
<langsyntaxhighlight Maplelang="maple">MeanAngle := proc( L )
uses Units:-Standard; # for unit-awareness
local u;
evalf( convert( argument( add( u, u = exp~( I *~ L ) ) ), 'units', 'radian', 'degree' ) )
end proc:</langsyntaxhighlight>
Applying this to the given data sets, we obtain:
<langsyntaxhighlight Maplelang="maple">> MeanAngle( [ 350, 10 ] *~ Unit(arcdeg) );
0.
 
Line 1,157 ⟶ 1,173:
 
> MeanAngle( [ 10, 20, 30 ] *~ Unit(arcdeg) );
20.00000000</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">meanAngle[data_List] := N@Arg[Mean[Exp[I data Degree]]]/Degree</langsyntaxhighlight>
{{out}}
<pre>meanAngle /@ {{350, 10}, {90, 180, 270, 360}, {10, 20, 30}}
Line 1,166 ⟶ 1,182:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function u = mean_angle(phi)
u = angle(mean(exp(i*pi*phi/180)))*180/pi;
end</langsyntaxhighlight>
<pre> mean_angle([350, 10])
ans = -2.7452e-14
Line 1,175 ⟶ 1,191:
mean_angle([10, 20, 30])
ans = 20.000
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
atan2 = function(y, x)
return 2 * atan((sqrt(x^2 + y^2) - x) / y)
end function
 
deg2rad = function(x); return x * pi / 180; end function
rad2deg = function(x); return x * 180 / pi; end function
 
meanAngle = function(angles)
xsum = 0; ysum = 0
for angle in angles
xsum += cos(deg2rad(angle))
ysum += sin(deg2rad(angle))
end for
return rad2deg(atan2(ysum / angles.len, xsum / angles.len))
end function
 
manyAngledOnes = [[350, 10], [90, 180, 270, 360], [10, 20, 30]]
 
for angles in manyAngledOnes
mean = meanAngle(angles)
print ["Mean of", angles, "is", mean].join(" ")
end for
</syntaxhighlight>
{{out}}
<pre>
Mean of [350, 10] is 0
Mean of [90, 180, 270, 360] is -90
Mean of [10, 20, 30] is 20.0
</pre>
 
=={{header|NetRexx}}==
{{trans|C}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 80
Line 1,212 ⟶ 1,260:
end angles
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,233 ⟶ 1,281:
=={{header|Nim}}==
{{works with|Nim|0.20.0+}}
<langsyntaxhighlight lang="nim">import math, complex
proc meanAngle(deg: openArray[float]): float =
Line 1,243 ⟶ 1,291:
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"</langsyntaxhighlight>
Output:
<pre>The 1st mean angle is: -1.614809932057922e-15 degrees
Line 1,251 ⟶ 1,299:
=={{header|Oberon-2}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE MeanAngle;
IMPORT
Line 1,284 ⟶ 1,332:
Out.LongRealFix(Mean(grades) * toDegs,15,9);Out.Ln;
END MeanAngle.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,293 ⟶ 1,341:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let pi = 3.14159_26535_89793_23846_2643
 
let deg2rad d =
Line 1,317 ⟶ 1,365:
test [90.0; 180.0; 270.0; 360.0];
test [10.0; 20.0; 30.0];
;;</langsyntaxhighlight>
or using the <code>Complex</code> module:
<langsyntaxhighlight lang="ocaml">open Complex
 
let mean_angle angles =
Line 1,325 ⟶ 1,373:
List.fold_left (fun sum a -> add sum (polar 1.0 (deg2rad a))) zero angles
in
rad2deg (arg sum)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,335 ⟶ 1,383:
=={{header|ooRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">/*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.*/
Line 1,358 ⟶ 1,406:
return left('angles='a,30) 'mean angle=' format(mA,,showDig,0)/1
 
::requires rxMath library;</langsyntaxhighlight>
{{out}}
<pre>angles=350 10 mean angle= 0
Line 1,365 ⟶ 1,413:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi)
meanDegrees(v)=meanAngle(v*Pi/180)*180/Pi
apply(meanDegrees,[[350, 10], [90, 180, 270, 360], [10, 20, 30]])</langsyntaxhighlight>
{{out}}
<pre>[360.000000, 296.565051, 20.0000000]</pre>
Line 1,375 ⟶ 1,423:
Tested with free pascal.
Try to catch very small cos values and set to 0.0 degrees " Error : Not meaningful" as http://rosettacode.org/wiki/Averages/Mean_angle#Euler_Math_Toolbox complains.
<langsyntaxhighlight lang="pascal">program MeanAngle;
{$IFDEF DELPHI}
{$APPTYPE CONSOLE}
Line 1,445 ⟶ 1,493:
 
setlength(a,0);
end.</langsyntaxhighlight>
;output:
<pre>
Line 1,453 ⟶ 1,501:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub Pi () { 3.1415926535897932384626433832795028842 }
 
sub meanangle {
Line 1,469 ⟶ 1,517:
 
print "The mean angle of [@$_] is: ", meandegrees(@$_), " degrees\n"
for ([350,10], [90,180,270,360], [10,20,30]);</langsyntaxhighlight>
{{out}}
<pre>
Line 1,479 ⟶ 1,527:
=={{header|Phix}}==
Copied from [[Averages/Mean_angle#Euphoria|Euphoria]], and slightly improved
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function MeanAngle(sequence angles)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom x = 0, y = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">MeanAngle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">angles</span><span style="color: #0000FF;">)</span>
for i=1 to length(angles) do
<span style="color: #004080;">atom</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
atom ai_rad = angles[i]*PI/180
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angles</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
x += cos(ai_rad)
<span style="color: #004080;">atom</span> <span style="color: #000000;">ai_rad</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">angles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">180</span>
y += sin(ai_rad)
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ai_rad</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">y</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ai_rad</span><span style="color: #0000FF;">)</span>
if abs(x)<1e-16 then return "not meaningful" end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return sprintf("%g",round(atan2(y,x)*180/PI,1e10))
<span style="color: #008080;">if</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">1e-16</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">"not meaningful"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%g"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">round</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">atan2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">180</span><span style="color: #0000FF;">/</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e10</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant AngleLists = {{350,10},{90,180,270,360},{10,20,30},{180},{0,180}}
for i=1 to length(AngleLists) do
<span style="color: #008080;">constant</span> <span style="color: #000000;">AngleLists</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">350</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">90</span><span style="color: #0000FF;">,</span><span style="color: #000000;">180</span><span style="color: #0000FF;">,</span><span style="color: #000000;">270</span><span style="color: #0000FF;">,</span><span style="color: #000000;">360</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">180</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">180</span><span style="color: #0000FF;">}}</span>
sequence ai = AngleLists[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AngleLists</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"%16v: Mean Angle is %s\n",{ai,MeanAngle(ai)})
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ai</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">AngleLists</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end for</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%16V: Mean Angle is %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ai</span><span style="color: #0000FF;">,</span><span style="color: #000000;">MeanAngle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ai</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,506 ⟶ 1,557:
=={{header|PHP}}==
{{trans|C}}
<langsyntaxhighlight lang="php"><?php
$samples = array(
'1st' => array(350, 10),
Line 1,528 ⟶ 1,579:
return rad2deg(atan2($y_part, $x_part));
}
?></langsyntaxhighlight>
{{out}}
<pre>Mean angle for 1st sample: -1.6148099320579E-15 degrees.
Line 1,535 ⟶ 1,586:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de meanAngle (Lst)
Line 1,548 ⟶ 1,599:
"The mean angle of ["
(glue ", " (mapcar round L '(0 .)))
"] is: " (round (meanAngle L))) )</langsyntaxhighlight>
{{out}}
<pre>The mean angle of [350, 10] is: 0.000
Line 1,555 ⟶ 1,606:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">averages: procedure options (main); /* 31 August 2012 */
declare b1(2) fixed initial (350, 10);
declare b2(4) fixed initial (90, 180, 270, 360);
Line 1,572 ⟶ 1,623:
end mean;
 
end averages;</langsyntaxhighlight>
Results (the final one brings up an error in inverse tangent):
<pre>
Line 1,583 ⟶ 1,634:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-MeanAngle ([double[]]$Angles)
{
Line 1,591 ⟶ 1,642:
[Math]::Atan2($y, $x) * 180 / [Math]::PI
}
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
@(350, 10), @(90, 180, 270, 360), @(10, 20, 30) | ForEach-Object {Get-MeanAngle $_}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,605 ⟶ 1,656:
 
=={{header|Processing}}==
<langsyntaxhighlight Processinglang="processing">void setup() {
println(meanAngle(350, 10));
println(meanAngle(90, 180, 270, 360));
Line 1,618 ⟶ 1,669:
}
return degrees(atan2(sum1, sum2));
}</langsyntaxhighlight>
{{out}}
<pre>-7.8025005E-6
Line 1,625 ⟶ 1,676:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">NewList angle.d()
 
Macro AE(x)
Line 1,654 ⟶ 1,705:
AE(10.0) : AE(20.0) : AE(30.0)
Debug StrD(mAngle(angle()),6) : ClearList(angle())
</syntaxhighlight>
</lang>
{{out}}
<pre>-0.000000
Line 1,662 ⟶ 1,713:
=={{header|Python}}==
{{works with|Python|2.6+}}
<langsyntaxhighlight lang="python">>>> from cmath import rect, phase
>>> from math import radians, degrees
>>> def mean_angle(deg):
Line 1,673 ⟶ 1,724:
The mean angle of [90, 180, 270, 360] is: -90.0 degrees
The mean angle of [10, 20, 30] is: 20.0 degrees
>>> </langsyntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
deg2rad <- function(x) {
x * pi/180
Line 1,710 ⟶ 1,761:
mean_deg(c(90, 180, 270, 360))
mean_deg(c(10, 20, 30))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,720 ⟶ 1,771:
=={{header|Racket}}==
The formula given above can be straightforwardly transcribed into a program:
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,736 ⟶ 1,787:
(mean-angle '(90 180 270 360))
(mean-angle '(10 20 30))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,748 ⟶ 1,799:
{{works with|Rakudo|2015.12}}
This solution refuses to return an answer when the angles cancel out to a tiny magnitude.
<syntaxhighlight lang="raku" perl6line># Of course, you can still use pi and 180.
sub deg2rad { $^d * tau / 360 }
sub rad2deg { $^r * 360 / tau }
Line 1,763 ⟶ 1,814:
[350, 10],
[90, 180, 270, 360],
[10, 20, 30];</langsyntaxhighlight>
{{out}}
<pre>-0.00 is the mean angle of 350 10
Line 1,816 ⟶ 1,867:
REXX statements
<br>into single lines would increase the program's bulk and detract from the main program.
<langsyntaxhighlight lang="rexx">/*REXX program computes the mean angle for a group of angles (expressed in degrees). */
call pi /*define the value of pi to some accuracy.*/
numeric digits length(pi) - 1; /*use PI width decimal digits of precision,*/
Line 1,870 ⟶ 1,921:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default internal inputs:}}
<pre>
Line 1,880 ⟶ 1,931:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Averages/Mean angle
 
Line 1,915 ⟶ 1,966:
ok
ok
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,921 ⟶ 1,972:
-90
20.000000
</pre>
 
=={{header|RPL}}==
≪ DEG → angles
≪ 0 1 angles SIZE '''FOR''' j
1 angles j GET R→C P→R + '''NEXT'''
angles SIZE / ARG
≫ ≫ ''''MEANG'''' STO
{{in}}
<pre>
{ 350 10 } MEANG
{ 90 180 270 360 } MEANG
{ 10 20 30 } MEANG
</pre>
{{out}}
<pre>
3: 0
2: -90
1: 20
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.
 
def deg2rad(d)
Line 1,940 ⟶ 2,010:
[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles|
puts "The mean angle of %p is: %f degrees" % [angles, mean_angle(angles)]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,950 ⟶ 2,020:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">
use std::f64;
// the macro is from
Line 1,994 ⟶ 2,064:
assert_diff!(20.0, mean_angle(&angles3), 0.001);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">trait MeanAnglesComputation {
import scala.math.{Pi, atan2, cos, sin}
 
Line 2,015 ⟶ 2,085:
assert(meanAngle(List(10, 20, 30)).round == 20, "Unexpected result with 10, 20, 30")
println("Successfully completed without errors.")
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 2,021 ⟶ 2,091:
{{trans|Common Lisp}}
 
<langsyntaxhighlight lang="scheme">
(import (srfi 1 lists)) ;; use 'fold' from library
 
Line 2,045 ⟶ 2,115:
(display " is ") (display (mean-angle angles)) (newline))
'((350 10) (90 180 270 360) (10 20 30)))
</syntaxhighlight>
</lang>
 
<pre>
Line 2,054 ⟶ 2,124:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
Line 2,083 ⟶ 2,153:
writeln(meanAngle([] (90.0, 180.0, 270.0, 360.0)) digits 4);
writeln(meanAngle([] (10.0, 20.0, 30.0)) digits 4);
end func;</langsyntaxhighlight>{{out}}
0.0000
90.0000
Line 2,089 ⟶ 2,159:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func mean_angle(angles) {
atan2(
Math.avg(angles.map{ .deg2rad.sin }...),
Line 2,098 ⟶ 2,168:
[[350,10], [90,180,270,360], [10,20,30]].each { |angles|
say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,107 ⟶ 2,177:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">mata
function meanangle(a) {
return(arg(sum(exp(C(0,a)))))
Line 2,120 ⟶ 2,190:
meanangle((10,20,30)*deg)/deg
20
end</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
@inlinable public func d2r<T: FloatingPoint>(_ f: T) -> T { f * .pi / 180 }
Line 2,144 ⟶ 2,214:
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])))")</langsyntaxhighlight>
 
{{out}}
Line 2,153 ⟶ 2,223:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc meanAngle {angles} {
set toRadians [expr {atan2(0,-1) / 180}]
set sumSin [set sumCos 0.0]
Line 2,162 ⟶ 2,232:
# Don't need to divide by counts; atan2() cancels that out
return [expr {atan2($sumSin, $sumCos) / $toRadians}]
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl"># A little pretty-printer
proc printMeanAngle {angles} {
puts [format "mean angle of \[%s\] = %.2f" \
Line 2,172 ⟶ 2,242:
printMeanAngle {350 10}
printMeanAngle {90 180 270 360}
printMeanAngle {10 20 30}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,181 ⟶ 2,251:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">double meanAngle(double[] angles) {
double y_part = 0.0;
double x_part = 0.0;
Line 2,201 ⟶ 2,271:
print("\nMean Angle for 2nd set : %lf degrees", meanAngle(angleSet2));
print("\nMean Angle for 3rd set : %lf degrees\n", meanAngle(angleSet3));
}</langsyntaxhighlight>
 
{{out}}
Line 2,211 ⟶ 2,281:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Base 1
Private Function mean_angle(angles As Variant) As Double
Dim sins() As Double, coss() As Double
Line 2,229 ⟶ 2,299:
Debug.Print Format(mean_angle([{90, 180, 270, 360}]), "##0")
Debug.Print Format(mean_angle([{10, 20, 30}]), "##0")
End Sub</langsyntaxhighlight>{{out}}
<pre>0
-90
Line 2,236 ⟶ 2,306:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Math
 
Module Module1
Line 2,253 ⟶ 2,323:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>0
-90
20</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">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")
}
}</syntaxhighlight>
 
{{out}}
<pre>
The mean angle of [350, 10] is: -2.6644363878955713e-14 degrees
The mean angle of [90, 180, 270, 360] is: -90 degrees
The mean angle of [10, 20, 30] is: 19.999999999999996 degree
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var meanAngle = Fn.new { |angles|
Line 2,282 ⟶ 2,383:
System.print("Mean for angles %(i) is : %(Fmt.f(6, meanAngle.call(angles), 2))")
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 2,292 ⟶ 2,393:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
def Pi = 3.14159265358979323846;
Line 2,313 ⟶ 2,414:
RlOut(0, MeanAng([4, 90, 180, 270, 360])); CrLf(0);
RlOut(0, MeanAng([3, 10, 20, 30])); CrLf(0);
]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,324 ⟶ 2,425:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn meanA(a1,a2,etc){
as:=vm.arglist.pump(List,"toFloat","toRad");
n:=as.len();
Line 2,330 ⟶ 2,431:
.atan2(as.apply("cos").sum(0.0)/n)
.toDeg()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,340 ⟶ 2,441:
20
</pre>
 
[[Category:Geometry]]
9,476

edits