实现数学公式时,溢​​出的问题 [英] Overflow issues when implementing math formulas

查看:156
本文介绍了实现数学公式时,溢​​出的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说,计算平均值时,启动+(最终开始)从/ 2不同(启动+端)/ 2,因为后者可能会导致溢出。我不明白为什么这第二个可能导致溢出而第一个没有。什么是实现一个数学公式,可避免溢出通用的规则。

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 can cause overflow while the first one does not. What are the generic rule to implement a math formula that can avoid overflow.

推荐答案

假设你正在使用一台计算机,其中最大的整数值是10,你要计算的5和7的平均水平。

Suppose you are using a computer where the maximum integer value is 10 and you want to compute the average of 5 and 7.

第一种方法(开始+(最终开始)/ 2)提供。

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

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

第二个方法(开始+端)/ 2给出了一个溢出,因为中间12值超过10,我们接受的最大值和越过了别的东西(如果你使用的是无符号数其一贯的以转回到零,但如果你的数字签名的,你可以得到一个负数!)。

The second method (begin + end)/2 gives an overflow, since the intermediate 12 value is over the maximum value of 10 that we accept and "wraps over" to something else (if you are using unsigned numbers its usual to wrap back to zero but if your numbers are signed you could get a negative number!).

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


当然,在真正的计算机的整数溢出在一个较大的值如2 ^ 32而不是10,但这个想法是一样的。不幸的是,有没有一般的方法来摆脱溢出,我知道的,它极大地取决于什么特定的算法所使用。而事件的话,事情变得更加复杂。你可以得到不同的行为,这取决于号码类型你是引擎盖下使用并有其他类型的数值误差担心,除了超过和下溢。


Of course, in real computers integers overflow at a large value like 2^32 instead of 10, but the idea is the same. Unfortunately, there is no "general" way to get rid of overflow that I know of, and it greatly depends on what particular algorithm you are using. And event then, things get more complicated. You can get different behaviour depending on what number type you are using under the hood and there are other kinds of numerical errors to worry about in addition to over and underflow.

这篇关于实现数学公式时,溢​​出的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆