I donβt know if there is any standard algorithm for this kind of problems, but it intrigues me, so Iβll try to develop an algorithm that will find the approximation I need.
Call the actual number in question r . Then first suppose that a can be negative, and in this case we can reduce the problem, and now we need to find a b such that the decimal part of sqrt(b) is a good approximation of the decimal part of r . Now we write r as r = xy with x being an integer and y decimal part.
Now: b = r^2 = (xy)^2 = (x + .y)^2 = x^2 + 2 * x * .y + .y^2 = 2 * x * .y + .y^2 (mod 1)
We can only find a x such that 0 = .y^2 + 2 * x * .y (mod 1) (approximately).
Filling x into the above formulas, we get b and then calculate a as a = r - b . (Of course, all these calculations should be carefully rounded.)
Now, while I'm not sure if there is a way to find this x without forcibly forcing. But even then, you can simply use a simple loop to find x well enough.
I am thinking of something similar (semi pseudo code):
max_diff_low = 0.01 // arbitrary accuracy max_diff_high = 1 - max_diff_low y = r % 1 v = y^2 addend = 2 * y x = 0 while (v < max_diff_high && v > max_diff_low) x++; v = (v + addend) % 1 c = (x + y) ^ 2 b = round(c) a = round(r - c)
Now, I think this algorithm is quite efficient, even allowing you to specify the desired approximation accuracy. One thing that could be done by turning it into an O (1) algorithm, calculates all x and puts them in the lookup table. If we consider only the first three decimal digits of r (for example), the lookup table will have only 1000 values, which is only 4 KB of memory (provided that 32-bit integers are used).
Hope this will be helpful in general. If someone finds something wrong with the algorithm, let me know in the comment and I will fix it.
EDIT: In reflecting, I give up my claim of effectiveness. In fact, as far as I can tell, there is no guarantee that the algorithm described above will ever end, and even if it does, it may take a long time to find a very large x that adequately solves the equation.
One could keep track of the best x found so far and lower the limits of accuracy over time to ensure that the algorithm completes quickly with a possible price of accuracy.
These problems, of course, do not exist if you simply pre-compute the lookup table.