November 2015 |
|
January 2016 |
#include <iostream>
#include <numeric>
#include <vector>
#include <algorithm>
template <typename T>
void compute_mean_stdev(std::vector<T>& v, T& mean, T& stdev) {
mean = std::accumulate(v.begin(), v.end(), 0.0) / v.size();
stdev = 0;
std::for_each (v.begin(), v.end(), [&](const T x) {stdev += (x - m) * (x - m);});
stdev = sqrt(stdev / (v.size()-1));
}
Why there is "N−1" in the standard deviation formula instead of "N"?
Because the mean is calculated from N events. So there are only N−1 degrees of freedom left to calculate the spread.
a = sin2(Δφ/2) + cosφ1 . cosφ2 . sin2(Δλ/2)
distance = 2 . R . atan2(√a, √(1−a)),
where φ is latitude, λ longitude, R earth's radius (= 6371 km). Here is a quick stand alone code.
//geo_distance_calculator.h
#pragma once
#include <iostream>
#include <cmath>
template <typename T>
float geo_distance_km(const T& lon1, const T& lat1, const T& lon2, const T& lat2)
{
const uint32_t R = 6371; // kilometers
constexpr float deg_to_red = M_PI / 180;
float phi1 = lat1 * deg_to_red;
float phi2 = lat2 * deg_to_red;
float dPhi = (lat2-lat1) * deg_to_red;
float dLam = (lon2-lon1) * deg_to_red;
float a = pow(sin(dPhi/2),2) + cos(phi1)*cos(phi2)*pow(sin(dLam/2),2);
return 2 * R * atan2(sqrt(a), sqrt(1-a));
}