9
We have a floating point number r between 0 and 1, and an integer p.
Find the fraction of integers with the smallest denominator, which approximates r with at least p-digit precision.
- Inputs:
r(a floating point number) andp(integer). - Outputs:
aandbintegers, wherea/b(as float) approximatesruntilpdigits.bis the possible smallest such positive integer.
For example:
- if
r=0.14159265358979andp=9, - then the result is
a=4687andb=33102, - because
4687/33102=0.1415926530119026.
Any solution has to work in theory with arbitrary-precision types, but limitations caused by implementations' fixed-precision types do not matter.
Precision means the number of digits after "0." in r. Thus, if r=0.0123 and p=3, then a/b should start with 0.012. If the first p digits of the fractional part of r are 0, undefined behavior is acceptable.
Win criteria:
- The algorithmically fastest algorithm wins. Speed is measured in O(p).
- If there are multiple fastest algorithms, then the shortest wins.
- My own answer is excluded from the set of the possible winners.
P.s. the math part is actually much easier as it seems, I suggest to read this post.
Why are you fiddling around with
padEndandmatch? Can't you justsliceeach string to the correct length and then subtract them? – Neil – 2017-09-18T09:14:00.663@Neil Sorry I hadn't catch your point. The added
padEndis used for testcasef(0.001,2)andf(0.3,2). – tsh – 2017-09-18T09:23:39.557I was thinking you could simplify down to something along the lines of
(r,p)=>{for(a=0,b=1;`${a/b}`.slice(0,p+2)-`${r}`.slice(0,p+2);a/b<r?a++:b++);return[a,b]}(not fully golfed). – Neil – 2017-09-18T09:27:49.270@Neil 120 -> 70 bytes. :) – tsh – 2017-09-18T09:56:48.393
Whoa, that's much better! – Neil – 2017-09-18T09:58:05.970