8
Given two arbitrarily precise decimal numbers 0 ≤ x < y ≤ 1, compute the shortest (in digits) binary number b such that x ≤ b < y.
Output the binary digits of b after the binary point as an array or a string of zeroes and ones. Note that the empty array means 0.0, by virtue of deleting trailing zeroes. This also makes sure that there is a unique correct answer for any range.
If you are unfamiliar with binary fractional numbers, they work just like decimal numbers:
Base 10 0.625 = 0.6 + 0.02 + 0.005 = 6 x 10^-1 + 2 x 10^-2 + 5 x 10^-3
Base 2 0.101 = 0.1 + 0.00 + 0.001 = 1 x 2^-1 + 0 x 2^-2 + 1 x 2^-3
| | |
v v v
Base 10 0.625 = 0.5 + 0 + 0.125
Built-ins that trivialize this problem are disallowed.
Examples:
0.0, 1.0 -> ""
0.1, 1.0 -> "1"
0.5, 0.6 -> "1"
0.4, 0.5 -> "0111"
Shortest code wins.
3Does "arbitrarily precise" mean "within the limits of your language's types," or do we have to support input of
(0.98983459823945792125172638374187268447126843298479182647, 0.98983459823945792125172638374187268447126843298479182648)
? Also, test cases would be helpful. – Doorknob – 2016-02-18T20:11:16.333@Doorknob Arbitrarily precise means that your answer should work for any input, up to limits of the physical machine (memory). So yes, that input must be supported. – orlp – 2016-02-18T20:13:14.507
Sort of dupe? – Martin Ender – 2016-02-18T21:27:33.863
@MartinBüttner Really close (wasn't aware of it), but this question requires arbitrary precision and output as bits. – orlp – 2016-02-18T21:30:12.517
1Aaaah the top-half-open interval x ≤ b < y is hard to deal with, it would be so much easier with x < b ≤ y. – xnor – 2016-02-19T01:51:31.273
@xnor Indeed, if I could guarantee 0 ≤ x < b ≤ y < 1 then I could do it in JavaScript in 171 bytes without even golfing:
(a,b)=>{a=a.slice(2);b=b.slice(2);r='0.';while(a[0]>4|b[0]<5){r+=+(a[0]>4);a=a.replace(/./g,(n,i)=>n*2%10+(a[i+1]>4));b=b.replace(/./g,(n,i)=>n*2%10+(b[i+1]>4))}return r+1}
– Neil – 2016-02-19T02:51:10.560