I've found that in some algorithms to find the middle point of a numeric range the next formula is used:
middle = low + ((high - low) / 2)
Yet, others use the next formula:
middle = (low + high) / 2
I've done some test and both formulas yield to the same correct middle result. My question is, do both always yield to the same result? or does any of them need to be used for specific scenarios or conditions?
If both are exactly the same, is there any reason why one would be used over the other?
(low + high) / 2would fail, namely in computer programming whenlowandhighhappened to be near the upper bound of their respective datatypes. You'd have an overflow error iflow + highwere too large. That said, this is a particularly uncommon occurrence and in most contexts you can safely ignore it. – JMoravitz Aug 31 '20 at 14:25