Search code examples
c++algorithmc++11medianminimize

Minimization of (z-xi)^2


If I want to find a median (it is equivalent to minimize a function |z - xi|), I can use the following code snippet:

std::vector<int> v{5, 6, 4, 3, 2, 6, 7, 9, 3};

std::nth_element(v.begin(), v.begin() + v.size()/2, v.end());
std::cout << "The median is " << v[v.size()/2] << '\n';

Is there something like this, to find "median" for minimization of (z-xi)^2? That is, I want to find an element of the array in which the sum of these functions will be minimal.


Solution

  • Given an array x1, x2, …, xn of integers, the real number z that minimizes ∑i∈{1,2,…,n} (z - xi)2 is the mean z* = (1/n) ∑i∈{1,2,…,n} xi. You want to call std::min_element with a comparator that treats xi as less than xj if and only if |n xi - n z*| < |n xj - n z*| (we use n z* = ∑i∈{1,2,…,n} xi to avoid floating-point arithmetic; there are ways to reduce the extra precision required).