# Find closest whole integer in equation

Given the following equations:

$$a=\frac{py+qx}{2pq}$$ $$b=\frac{py-qx}{2pq}$$

Where p and q are some real constant number. And $(x, y)$ are some arbitrary real number. Any number can be inputted as $(x, y)$ but only those which produce whole integers for $a$ and $b$ respectively, are considered valid. Given these conditions, how can I find the valid $(x_1, y_1)$ values whose euclidean distance to the inputted $(x, y)$ is minimal?

E.g. for clarification. Given $p=1.6$ and $q=0.8$. The user inputs $(x,y) = (0, 1.5)$. This produces $(a,b)=(0.9375,0.9375)$ as this is not an integer value it is not considered valid. The next closest input which would produce an integer would be (0, 1.6). We'll call this $(x1,y1) = (0,1.6)$. Given the user inputs $(x,y)$ how can I return the closest valid position of $(x1,y1)$?.

This is a follow-up question with better clarifcation from the previous one here.

• Are $p$ and $q$ fixed? Also, for example, if the inputted $(x,y)=(0,0)$ what is the outputted value? This question seems to be unclear. What are the two points from which we have to minimize the Euclidean distance? – S.C.B. Jan 17 '17 at 0:22
• What do you want to minimize? The distance of the pair $(x, y)$ to the origin? Or the distance of $(x, y)$ to the resulting $(a, b)$? – RGS Jan 17 '17 at 0:25
• @S.C.B. I'm doing this in a programming application, so they should be modifiable for different situations. But for the sake of the argument here, they will remain fixed, in my current application $p=1.6$ and $q=0.8$ so the outputted value for $(x,y)=(0,0)$ is $(a,b)=(0, 0)$. The next real integer for $(a, b)$, i.e. when $(a, b) = (1, 1)$ is when $(x, y)=(0, 1.6)$ given that $p=1.6$ and $q=0.8$ – Manmax75 Jan 17 '17 at 0:36
• @ManMax75 Why isn't $(0,0)$ considered an integer output? – S.C.B. Jan 17 '17 at 0:37
• @S.C.B. Sorry, it is, I meant the next valid integer – Manmax75 Jan 17 '17 at 0:38

Given that $a$ and $b$ must be integers, we know that $a+b$ and $a-b$ are also integers.
$$\begin{cases}a + b = \frac{2py}{2pq}\\ a - b = \frac{2qx}{2pq}\end{cases}$$
From which one concludes that $q | y$ and $p | x$.
• Unfortunately this allows for cases like $(a, b) = (0.5, 0.5)$ where combining or subtracting them produces an integer but the individual parts are not integers, which are therefore invalid. – Manmax75 Jan 17 '17 at 1:51
• @Manmax75 indeed but writing $y = kq$ and similarly for $x$, and substituting in your expressions, yields further information about $x, y$ – RGS Jan 17 '17 at 1:54