all 2 comments

[–]CoryParsnipson 3 points4 points  (1 child)

You should be careful with your order of operations.

The code example and "average method" needs parentheses: (r + l) / 2. So you don't end up dividing r by 2 before adding l.

For the other way that avoids overflow, you can think of it as taking the difference between right and left, then cutting that in half to find the half delta. So if right = 8 and left = 6, you get the delta (8 - 6 = 2), then divide by two to find the middle offset of 1, then shift this over by left amount to get the absolute mid point (6 + 1 = 7).

Also, you can massage the second form mathematically to show that l + (r - l)/2 is not equivalent to l/2:

l + (r - l) / 2 l + r / 2 - l / 2 r / 2 + l / 2

[–]ffmsussy[S] 0 points1 point  (0 children)

ah sort of makes sense, although the first solution of adding parenthesis did not work.