WeixiangYan/CodeTransOcean huggingface dataset:
Task: Object serialization





Java: import java.io.*;


class Entity implements Serializable {
    
    
    static final long serialVersionUID = 3504465751164822571L;
    String name = "Entity";
    public String toString() { return name; }
}

class Person extends Entity implements Serializable {
    static final long serialVersionUID = -9170445713373959735L;
    Person() { name = "Cletus"; }
}

public class SerializationTest {
    public static void main(String[] args) {
        Person instance1 = new Person();
        System.out.println(instance1);

        Entity instance2 = new Entity();
        System.out.println(instance2);

        
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat")); 

            out.writeObject(instance1); 
            out.writeObject(instance2);
            out.close();
            System.out.println("Serialized...");
        } catch (IOException e) {
            System.err.println("Something screwed up while serializing");
            e.printStackTrace();
            System.exit(1);
        }

        
        try {
            ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat")); 

            Object readObject1 = in.readObject(); 
            Object readObject2 = in.readObject(); 
            in.close();
            System.out.println("Deserialized...");

            System.out.println(readObject1);
            System.out.println(readObject2);
        } catch (IOException e) {
            System.err.println("Something screwed up while deserializing");
            e.printStackTrace();
            System.exit(1);
        } catch (ClassNotFoundException e) {
            System.err.println("Unknown class for deserialized object");
            e.printStackTrace();
            System.exit(1);
        }
    }
}
Task: Object serialization







Python: 




import pickle

class Entity:
	def __init__(self):
		self.name = "Entity"
	def printName(self):
		print self.name

class Person(Entity): 
	def __init__(self): 
		self.name = "Cletus" 

instance1 = Person()
instance1.printName()

instance2 = Entity()
instance2.printName()

target = file("objects.dat", "w") 


pickle.dump((instance1, instance2), target) 
target.close() 
print "Serialized..."


target = file("objects.dat") 
i1, i2 = pickle.load(target)
print "Unserialized..."

i1.printName()
i2.printName()
Task: Object serialization




Go: package main

import (
    "encoding/gob"
    "fmt"
    "os"
)

type printable interface {
    print()
}

func main() {
    
    animals := []printable{
        &Animal{Alive: true},
        &Cat{},
        &Lab{
            Dog:   Dog{Animal: Animal{Alive: true}},
            Color: "yellow",
        },
        &Collie{Dog: Dog{
            Animal:           Animal{Alive: true},
            ObedienceTrained: true,
        }},
    }

    
    fmt.Println("created:")
    for _, a := range animals {
        a.print()
    }

    
    f, err := os.Create("objects.dat")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, a := range animals {
        gob.Register(a)
    }
    err = gob.NewEncoder(f).Encode(animals)
    if err != nil {
        fmt.Println(err)
        return
    }
    f.Close()

    
    f, err = os.Open("objects.dat")
    if err != nil {
        fmt.Println(err)
        return
    }
    var clones []printable
    gob.NewDecoder(f).Decode(&clones)
    if err != nil {
        fmt.Println(err)
        return
    }

    
    fmt.Println("\nloaded from objects.dat:")
    for _, c := range clones {
        c.print()
    }
}

type Animal struct {
    Alive bool
}

func (a *Animal) print() {
    if a.Alive {
        fmt.Println("   live animal, unspecified type")
    } else {
        fmt.Println("   dead animal, unspecified type")
    }
}

type Dog struct {
    Animal
    ObedienceTrained bool
}

func (d *Dog) print() {
    switch {
    case !d.Alive:
        fmt.Println("   dead dog")
    case d.ObedienceTrained:
        fmt.Println("   trained dog")
    default:
        fmt.Println("   dog, not trained")
    }
}

type Cat struct {
    Animal
    LitterBoxTrained bool
}
    
func (c *Cat) print() {
    switch {
    case !c.Alive:
        fmt.Println("   dead cat")
    case c.LitterBoxTrained:
        fmt.Println("   litter box trained cat")
    default:
        fmt.Println("   cat, not litter box trained")
    }
}

type Lab struct {
    Dog 
    Color string
}   

func (l *Lab) print() {
    var r string
    if l.Color == "" {
        r = "lab, color unspecified"
    } else {
        r = l.Color + " lab"
    }
    switch {
    case !l.Alive:
        fmt.Println("   dead", r)
    case l.ObedienceTrained:
        fmt.Println("   trained", r)
    default:
        fmt.Printf("   %s, not trained\n", r)
    }
}   

type Collie struct {
    Dog 
    CatchesFrisbee bool
}   

func (c *Collie) print() {
    switch {
    case !c.Alive:
        fmt.Println("   dead collie")
    case c.ObedienceTrained && c.CatchesFrisbee:
        fmt.Println("   trained collie, catches frisbee")
    case c.ObedienceTrained && !c.CatchesFrisbee:
        fmt.Println("   trained collie, but doesn't catch frisbee")
    case !c.ObedienceTrained && c.CatchesFrisbee:
        fmt.Println("   collie, not trained, but catches frisbee")
    case !c.ObedienceTrained && !c.CatchesFrisbee:
        fmt.Println("   collie, not trained, doesn't catch frisbee")
    }
}
Task: Object serialization






PHP: $myObj = new Object();
$serializedObj = serialize($myObj);
Task: Object serialization






PHP: $myObj = new Object();
$serializedObj = serialize($myObj);






Ada: with Ada.Calendar; use Ada.Calendar;

package Messages is
   type Message is tagged record
      Timestamp : Time;
   end record;
  
   procedure Print(Item : Message);
   procedure Display(Item : Message'Class);

   type Sensor_Message is new Message with record
      Sensor_Id : Integer;
      Reading : Float;
   end record;
   
   procedure Print(Item : Sensor_Message);
   
   type Control_Message is new Message with record
      Actuator_Id : Integer;
      Command     : Float;
   end record;
  
   procedure Print(Item : Control_Message);
  
end Messages;
Task: Averages_Mean angle



C#: 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 });
    }
}









Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle

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











Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle


C++: #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;
}










Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle




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








Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle





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







Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle







Python: >>> 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
>>>





Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle








VB: 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




Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;

procedure Mean_Angles is

   type X_Real is digits 4;      
   subtype Real is X_Real range 0.0 .. 360.0; 
   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; 
      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);
        
        
   end Mean_Angle;

begin
   Put(Mean_Angle((10.0, 20.0, 30.0)));     Ada.Text_IO.New_Line;    
   Put(Mean_Angle((10.0, 350.0)));          Ada.Text_IO.New_Line;    
   Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); 
end Mean_Angles;
Task: Averages_Mean angle

C: #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;
}
Task: Averages_Mean angle



C#: 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 });
    }
}
Task: Averages_Mean angle


C++: #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;
}
Task: Averages_Mean angle





Java: 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);
    }
}
Task: Averages_Mean angle







Python: >>> 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
>>>
Task: Averages_Mean angle








VB: 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
Task: Averages_Mean angle




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