const mid = Math.floor((right + left) / 2); susceptible to overflow? EDIT: Hm, perhaps not (in JS). Number.MAX_SAFE_INTEGER is much greater than I expected.
Not in Javascript, where everything is a double precision float. You would lose precision at about 2^51, but that’s not a limit that will meaningfully affect us for good while.
I've used it as a very simple equation solver in a pinch. Yes, it's a very naive approach for most equations, but getting started solving it satisfactory with a solution given is very welcome.
If f is monotonic and continuous, you can solve f(x) = y for x by successively narrowing an interval [a, b] where f(a) <= y <= f(b) (or vice versa for decreasing functions). In the case that the range of f spans the entire real numbers, the initial range can be determined as the smallest range [-2^k, 2^k] where k is an integer (a strategy often used for open-ended binary search).
Regarding "very simple" - as I recall from some book, first bug-free implementation appeared only after several years after invention / initial description of the algorithm. From wikipedia: "A study published in 1988 shows that accurate code for it is only found in five out of twenty textbooks" (https://en.wikipedia.org/wiki/Binary_search_algorithm).
This eliminates all branches from the body of the loop (gets compiled to conditional move). It's also more general because it can be used to find the right position to insert a new element in a sorted array.
How so? Are you talking about (high + low)/2? Whether that is correct depends on the language. With 64 bit arithmetic it's correct in practice, and with arbitrary size arithmetic it's correct in practice and in theory. It only really causes problems if you're using 32 bit arithmetic on a 64 bit machine.
Actually, I can definitely say that this version is not broken, i.e. I've formally proven it to be mathematically correct assuming that:
1. high and low are bigints (such as when using Python, for example) 2. the input array is sorted (needed for any binary search algorithm) 3. this missing code at the bottom is added:
if (0 <= low && low < arr.length) {
if (arr[low] == x) {
return low;
}
}
return -1; // (or "raise Not_found" or whatever you use to indicate that 'x' was not found).
You can find the formal proof in WhyML below. This includes proofs that:
1. all array accesses are in bounds [checked automatically] 2. there is no undefined behavior (such as division by zero) [checked automatically] 3. the function always terminates [enforced automatically, proven with the help of the 'variant' clause] 4. there are no overflows [checked automatically, not possible since we're using bigints] 5. if an index is returned, the array has an element with value equal to x at that index [the 'ensures' clause] 6. if instead the function returns "not found", the array does not have any element with a value equal to x [the 'raises' clause] ... all this assuming that the input array is sorted [the 'requires' clause] Code + proof here (it makes more sense if you can read OCaml syntax): https://clbin.com/jbTk8
Awesome! Interesting that it can prove that given only the loop invariant.
The inner loop could be factored to a subroutine with the following contract: let P be a predicate on the integers such that (i <= j) => (P(i) => P(j)), and let low be such that P(low) = false and high such that P(high) = true. The subroutine returns i such that P(i) = false and P(i+1) = true. The subroutine further promises to only call P(k) on low < k < high. This may be applied to the predicate P(k) = (x <= arr[k]) on the range (low,high) = (-1,arr.length) to find the point at which the predicate flips from false to true (we're essentially pretending to know that there is a small value at arr[-1] and a large value at arr[arr.length], and the subroutine promises to only call P(k) on values strictly between -1 and arr.length). Is it possible to do this with WhyML?
Ok, so this proved to be more difficult than I anticipated and it took me a while, but fortunately I really enjoyed the challenge!
It seems that the answer is definitely "yes", it can be done with WhyML. There are a few minor caveats: 1. I had to change the function with the while loop to return an option instead of raising the Not_found exception, which makes the code a bit uglier. This is because I ran into the following bug in Why3 (it's already fixed in the master branch, but not in the most recent release): https://gitlab.inria.fr/why3/why3/issues/214 2. It turns out that the value of "high" is not statically known at compile time, because it depends on the size of the array. So I changed "high" to be a function of the array rather than a constant (I did the same to "low" for consistency). 3. Similarly and consequently, the predicate P(i) is not only a function of "i". It's also a function of the value being searched for ("x"), i.e. if P(i) is true or not depends on which value you're searching for. This also means that P() is also a function of the specific array being searched for (because some arrays may have "x" but others not). 4. You said that "we're pretending to know that there is a small value at arr[-1] and a large value at arr[arr.length]", but unless I misunderstood something, we can't actually pretend that, this must be written in the code somewhere, otherwise it won't work. For simplicity, I have chosen to implement those rules in the predicate itself. However, this is also enforced by the function with the while loop, i.e., it always makes sure that whatever predicate you have chosen, it has to implement those rules. I am sure that this could be changed, but I think it would complicate the proofs. The result is that in module "GenericBinarySearch", like the name says, we have a neat generic binary search function which works with any predicate P (called "pred" in the code), any function "low", any function "high" and for any type. And in module "ArrayBinarySearch" we have an instantiation of "GenericBinarySearch" which works for sorted arrays! Also note that the axiom in the code is only an axiom in the generic module (it specifies what must be true of P()), but when the generic module is instantiated, Why3 verifies that the axiom is actually true for the specific instance of the predicate (so there is no cheating). You can find the code in the link below. Enjoy! https://clbin.com/Ov3NX
`git bisect` is an indispensible git trick. You give it commit where you know the bug exists, and one where you know it doesn't and it'll use binary search to help you find where the bug came from. It's absolutely wonderful.
I always struggle to see why people bang on about git bisect. You need tests to make it work. If you have tests, why aren't you running them continuously? If you're running them continuously, why do you need git bisect?
Yep, I use this all the time to figure out which SVN commit introduced a bug (run the last deployed version and verify it didn't have the bug, then binary search the commits in-between that and HEAD until I figure out which one caused it).
Comments (491) 209 threads
Show all comments
Showing thread 8 of 209
JS implementation: https://gist.github.com/netgusto/90c8e0e7019a832cbf95eac58e1...
const mid = Math.floor((right + left) / 2);
susceptible to overflow?
EDIT: Hm, perhaps not (in JS). Number.MAX_SAFE_INTEGER is much greater than I expected.
const mid = Math.floor(left + (right - left) / 2);
https://stackoverflow.com/q/27167943
https://ai.googleblog.com/2006/06/extra-extra-read-all-about...
EDIT: legibility
Continue this thread — 2 replies
Continue this thread — 4 replies
1. high and low are bigints (such as when using Python, for example)
You can find the formal proof in WhyML below. This includes proofs that:2. the input array is sorted (needed for any binary search algorithm)
3. this missing code at the bottom is added:
1. all array accesses are in bounds [checked automatically]
2. there is no undefined behavior (such as division by zero) [checked automatically]
3. the function always terminates [enforced automatically, proven with the help of the 'variant' clause]
4. there are no overflows [checked automatically, not possible since we're using bigints]
5. if an index is returned, the array has an element with value equal to x at that index [the 'ensures' clause]
6. if instead the function returns "not found", the array does not have any element with a value equal to x [the 'raises' clause]
... all this assuming that the input array is sorted [the 'requires' clause]
Code + proof here (it makes more sense if you can read OCaml syntax): https://clbin.com/jbTk8
The inner loop could be factored to a subroutine with the following contract: let P be a predicate on the integers such that (i <= j) => (P(i) => P(j)), and let low be such that P(low) = false and high such that P(high) = true. The subroutine returns i such that P(i) = false and P(i+1) = true. The subroutine further promises to only call P(k) on low < k < high.
This may be applied to the predicate P(k) = (x <= arr[k]) on the range (low,high) = (-1,arr.length) to find the point at which the predicate flips from false to true (we're essentially pretending to know that there is a small value at arr[-1] and a large value at arr[arr.length], and the subroutine promises to only call P(k) on values strictly between -1 and arr.length).
Is it possible to do this with WhyML?
Your question is very interesting and I think the answer is 'yes'. I will try to implement it and report back.
It seems that the answer is definitely "yes", it can be done with WhyML.
There are a few minor caveats:
1. I had to change the function with the while loop to return an option instead of raising the Not_found exception, which makes the code a bit uglier. This is because I ran into the following bug in Why3 (it's already fixed in the master branch, but not in the most recent release): https://gitlab.inria.fr/why3/why3/issues/214
2. It turns out that the value of "high" is not statically known at compile time, because it depends on the size of the array. So I changed "high" to be a function of the array rather than a constant (I did the same to "low" for consistency).
3. Similarly and consequently, the predicate P(i) is not only a function of "i". It's also a function of the value being searched for ("x"), i.e. if P(i) is true or not depends on which value you're searching for. This also means that P() is also a function of the specific array being searched for (because some arrays may have "x" but others not).
4. You said that "we're pretending to know that there is a small value at arr[-1] and a large value at arr[arr.length]", but unless I misunderstood something, we can't actually pretend that, this must be written in the code somewhere, otherwise it won't work. For simplicity, I have chosen to implement those rules in the predicate itself. However, this is also enforced by the function with the while loop, i.e., it always makes sure that whatever predicate you have chosen, it has to implement those rules. I am sure that this could be changed, but I think it would complicate the proofs.
The result is that in module "GenericBinarySearch", like the name says, we have a neat generic binary search function which works with any predicate P (called "pred" in the code), any function "low", any function "high" and for any type.
And in module "ArrayBinarySearch" we have an instantiation of "GenericBinarySearch" which works for sorted arrays!
Also note that the axiom in the code is only an axiom in the generic module (it specifies what must be true of P()), but when the generic module is instantiated, Why3 verifies that the axiom is actually true for the specific instance of the predicate (so there is no cheating).
You can find the code in the link below. Enjoy!
https://clbin.com/Ov3NX
Continue this thread — 6 replies
Continue this thread — 6 replies
The complexity is O(log log n), under the assumption of a uniform distribution of the data.
https://en.wikipedia.org/wiki/Interpolation_search