1

I was working on computer science problem on LeetCode website. The solution required that the midpoint be calculated between two numbers, lets call them start and end. Ultimately my solution passed the tests. The issue is that one of the other solutions I found had a similar solution, but it calculated the midpoint differently.

This is how I calculated it: mid = (start + end) / 2
This is how the other solution calculated it: mid = start + (end - start) / 2

Are these two functions equivalent? I tried to use my math skills, but they seem to have deteriorated over the decades. This is what I came up with so far, but just need some insight. (start + end) / 2 = start + (end - start) / 2
start + end = (start + (end - start)/2) * 2
start + end = 2 * start + (end - start)
start + end = start + end

  • 4
    You can just expand out the second equation: $m=s+(e-s)/2=s-s/2+e/2=s/2+e/2=(s+e)/2$ – Schach21 Jul 22 '22 at 03:19
  • 3
    The two formulas are mathematically equivalent, but may potentially produce different numeric results depending on the data types, precision and rounding modes. This, however, would no longer be a math question but a programming one. – dxiv Jul 22 '22 at 04:06

0 Answers0