Optimal rounding a sequence of reals to integers

This is an MIQP (Mixed Integer Quadratic Programming) problem. This version is the easy one: convex. That means there are quite a few good solvers available to handle this. Still, finding proven global optimal solutions is often difficult. On the other hand, solvers find typically good solutions very quickly. For $n=1000$ a good solver should take no more than a few seconds to find a global optimal solution.


Omitting the constraint, $x_i = \lfloor c_i \rceil$ is clearly optimal. Now if you perform scaling like you propose to satisfy the constraint, you move "large numbers" further away from $c_i$ than necessary. For example, with $c_1=10$, $c_2=20$, $d=10$, your solution approach results in $x=(3,7)$, while $x=(0,10)$ is a better solution (objective value $\sqrt{218}$ vs $\sqrt{200}$).

Intuitively, all numbers in the final solution should be equally close to $c_i$, since deviations are penalized quadratically. So, the first thing you do is set $x_i = \lfloor c_i \rceil$ and compute $t = \sum_i x_i$. If $t=d$, you are done. Otherwise, you have to adjust. Let me assume $t > d$ (the case for $t < d$ is similar). Then you need to subtract a total $d-t$ from the $x_i$. The best numbers to take this from are the ones you rounded up, so round them down instead, the ones with largest $x_i-c_i$ first. Then subtract $1$ from each $x_i$ in the order of $c_i-x_i$ (smallest first) until $\sum_i x_i = d$. If at the start, $d-t$ is large, you can start by subtracting $\lfloor (d-t)/n \rfloor$ from each number.