Skip to content

Instantly share code, notes, and snippets.

@facundofarias
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save facundofarias/95fc76395dc497cb9d2f to your computer and use it in GitHub Desktop.
Save facundofarias/95fc76395dc497cb9d2f to your computer and use it in GitHub Desktop.
Time circular mean calculation
/**
* Created by ffarias on 2/4/14.
*/
var meanTimeOfDay =
{
timeToDegrees: function (datetime) {
return (360 * datetime.getHours() / 24.0 + 360 * datetime.getMinutes() / (24 * 60.) + 360 * datetime.getSeconds() / (24 * 3600.0));
},
timeFromDegrees: function (angle) {
var time = {};
var totalSeconds = 24 * 60 * 60 * angle / 360;
time.seconds = Math.floor(totalSeconds % 60);
time.minutes = Math.floor((totalSeconds % 3600 - time.seconds) / 60);
time.hours = Math.floor(totalSeconds / 3600);
return time;
},
meanAngle: function (angles) {
var y_part = 0;
var x_part = 0;
for (var i=0; i < angles.length; i++)
{
x_part += Math.cos(angles[i] * Math.PI / 180);
y_part += Math.sin(angles[i] * Math.PI / 180);
}
return Math.atan2(y_part/angles.length, x_part/angles.length) * 180 / Math.PI;
},
// Input hours: 23:00:17 23:40:20 00:12:45 00:17:19
// Expected result: "The mean time is : 23:47:43"
calculateMeanTimeOfDay: function (){
var input = [
new Date(2014,2,4,23,0,17),
new Date(2014,2,4,23,40,20),
new Date(2014,2,5,0,12,45),
new Date(2014,2,5,0,17,19)
];
var inputOnDegrees = new Array();
for (var i = 0; i < input.length; i++) {
inputOnDegrees.push(this.timeToDegrees(input[i]));
}
var meanTime = this.timeFromDegrees( 360 + this.meanAngle(inputOnDegrees));
console.log('Hours' + meanTime.hours, ' Min' + meanTime.minutes, ' Seconds' + meanTime.seconds);
}
}
meanTimeOfDay.calculateMeanTimeOfDay();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment