# Approximating a matrix so that 1) all rows sum to one and 2) all values have max 6 digits.

Let consider a big matrix with values ranging from 0 to 1 (included). Each row sums to values that are lower than 1, extremely close to 1 but not exactly 1.

I'd like to make sure that 1) each row sums to 1 and 2) no element has more than 6 digits. The goal is to find a method that minimizes the approximation. We may for example want to minimize the sum of the squared differences between original values of the matrix and the values at the end.

Coded in R: let mat be the matrix of interest. I first multiplied each element by the sum of its row to make sure each row sums up to 1

mat = mat / rowSums(mat)


Then, I wanted to make sure than no value has more than 6 digits. So I rounded all values

mat = round(mat,6)


As a result of this last operation, all rows don't sum to exactly 1 anymore! If I were to do the opposite, that is rounding in first place:

mat = round(mat,6)
mat = mat / rowSums(mat)


I would then have values that have more than 6 digits!

What is the most (or one of the most) optimal way to make sure that all rows sum up to 1 and that no values has more than 6 digits with as little approximation as possible?

If needed I welcome people to define "as little approximation as possible" as the technic that minimizes the sum of squared differences between original values of mat and the values at the end.

In the context of the original problem, let $r$ be a row of the original matrix, and $r_f$ be the row of the floor of $r$, to 6 decimal places, in each entry. Add up the entries of $r_f$, subtract from $1$, and multiply by $10^6$. Call this $n$. $n$ is how many entries need to be rounded up instead of down. Set $r_d-=r-r_f$. Find the indices of the $n$ largest entries of $r_d$, and add $10^{-6}$ to those indices in $r_f$. This is your desired row.