c++ - Overflow issues when implementing math formulas -


i heard that, when computing mean value, start+(end-start)/2 differs (start+end)/2 because latter can cause overflow. not quite understand why second 1 can cause overflow while first 1 not. generic rule implement math formula can avoid overflow.

suppose using computer maximum integer value 10 , want compute average of 5 , 7.

the first method (begin + (end-begin)/2) gives

5 + (7-5)/2 == 5 + 2/2 == 6 

the second method (begin + end)/2 gives overflow, since intermediate 12 value on maximum value of 10 accept , "wraps over" else (if using unsigned numbers usual wrap 0 if numbers signed negative number!).

12/2 => overflow occurs => 2/2 == 1 

of course, in real computers integers overflow @ large value 2^32 instead of 10, idea same. unfortunately, there no "general" way rid of overflow know of, , depends on particular algorithm using. , event then, things more complicated. can different behaviour depending on number type using under hood , there other kinds of numerical errors worry in addition on , underflow.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -