如何避免expr中的溢出.A B C D [英] How to avoid overflow in expr. A * B - C * D

查看:59
本文介绍了如何避免expr中的溢出.A B C D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算一个看起来像这样的表达式: A * B-C * D ,其类型为: signed long long int A,B,C,D; 每个数字可能确实很大(不会溢出其类型).虽然 A * B 可能会导致溢出,但同时 A * B-C * D 表达式可能确实很小.如何正确计算?

I need to compute an expression which looks like: A*B - C*D, where their types are: signed long long int A, B, C, D; Each number can be really big (not overflowing its type). While A*B could cause overflow, at same time expression A*B - C*D can be really small. How can I compute it correctly?

例如: MAX * MAX-(MAX-1)*(MAX + 1)== 1 ,其中 MAX = LLONG_MAX-n 和n-一些自然数字.

For example: MAX * MAX - (MAX - 1) * (MAX + 1) == 1, where MAX = LLONG_MAX - n and n - some natural number.

推荐答案

我想这似乎太琐碎了.但是 A * B 可能会溢出.

This seems too trivial I guess. But A*B is the one that could overflow.

您可以执行以下操作,而不会失去精度

You could do the following, without losing precision

A*B - C*D = A(D+E) - (A+F)D
          = AD + AE - AD - DF
          = AE - DF
             ^smaller quantities E & F

E = B - D (hence, far smaller than B)
F = C - A (hence, far smaller than C)

此分解可以进一步完成.
正如@Gian指出的那样,如果类型为unsigned long long,则在减法操作期间可能需要小心.

This decomposition can be done further.
As @Gian pointed out, care might need to be taken during the subtraction operation if the type is unsigned long long.

例如,在您遇到问题的情况下,只需进行一次迭代,

For example, with the case you have in the question, it takes just one iteration,

 MAX * MAX - (MAX - 1) * (MAX + 1)
  A     B       C           D

E = B - D = -1
F = C - A = -1

AE - DF = {MAX * -1} - {(MAX + 1) * -1} = -MAX + MAX + 1 = 1

这篇关于如何避免expr中的溢出.A B C D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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