Overflow issues when implementing math formulas

前端 未结 4 946
陌清茗
陌清茗 2020-12-21 02:02

I heard that, when computing mean value, start+(end-start)/2 differs from (start+end)/2 because the latter can cause overflow. I do not quite understand why this second one

4条回答
  •  被撕碎了的回忆
    2020-12-21 02:34

    Both your formulas will overflow, but under different circumstances:

    • The (start+end) part of your (start+end)/2 formula will overflow when start and end are both close to the integer limit on the same side of the range (i.e. both positive or both negative).
    • The (end-start) part of your start+(end-start)/2 formula will overflow when start is positive and end is negative, and both values are close to the respective ends of the representable integer values.

    There are no "generic" rules, you do it case-by-case: look at parts of your formula, think of situations that could cause overflow, and come up with ways to avoid it. For example, the start+(end-start)/2 formula can be shown to avoid overflow when you average values with the same sign.

    This is the hard way; the easy way is to use higher-capacity representations for intermediate results. For example, if you use long long instead of int to do intermediate calculations and copy the results back to int only when you are done, you will avoid overflow assuming that the end result fits in an int.

提交回复
热议问题