Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Oiling my tablet
Message
From
29/04/2013 10:39:41
 
 
General information
Forum:
Javascript
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
01572116
Message ID:
01572159
Views:
51
>So far, so good:
        public static void Main()
>        {
>            var result = GetAverage(new int[] {357, 2, 359, 356, 4, 2, 355, 22});  //Result : 2
>            result = GetAverage(new int[] { 180, 182, 175, 178, 183, 185, 177, 172 });   //Result: 44 :-{
>        }
>
>        public static double GetAverage(int[] values)
>        {
>            double c = 0;
>            double s = 0;
>
>            foreach (int i in values)
>            {
>                double r = DegreeToRadian(i);
>                c += Math.Cos(r);
>                s += Math.Sin(r);
>            }
>
>            double a = Math.Atan2(s, c);
>
>            return RadianToDegree(a);
>        }
>
>        public static double DegreeToRadian(double angle)
>        {
>            return Math.PI * angle / 180.0;
>        }
>
>        public static double RadianToDegree(double angle)
>        {
>            return angle * (180.0 / Math.PI);
>        }
> More testing......


Took a bit of your code - adding vectors
To my surprise Atan2() is clever - and returns the right quadrant
		public static int GetAverage(IEnumerable<int> readings)
		{
			double s = 0.0, c = 0.0;
			bool haveData = false;

			foreach (int value in readings)
			{
				double rads = DegreeToRadian(value);
				
				s += Math.Sin(rads);
				c += Math.Cos(rads);
				haveData = true;
			}
			
			int result = 0;
			if (haveData)
			{
				double rads;

				if (c == 0)
				{
					rads = s >= 0.00 ? Math.PI / 2.0 : -Math.PI / 2.0;
				}
				else
					rads = Math.Atan2(s, c);

				result  = (int)RadianToDegree(rads);

			}
			return result;
		}
		public static double DegreeToRadian(double degrees)
		{
			return Math.PI * Modulo(degrees, 360.00) / 180.0;
		}

		 public static double RadianToDegree(double rads)
		{
			return Modulo(rads, Math.PI * 2) * (180.0 / Math.PI);
		}
		public static double Modulo(double dividend, double divisor)
		{
			return (dividend % divisor)
					+ (Math.Sign(dividend) * Math.Sign(divisor) >= 0 ? 0 : divisor);
		}
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform