不正确的浮点数学? [英] Incorrect floating point math?
问题描述
这是一个问题,这让我完全不知道过去几个小时...
我有一个方程硬编码在我的程序:
double s2;
s2 = - (0 * 13)/ 84 + 6 / 42-0 / 84 + 24/12 +(6 * 13)/ 42;
每次运行程序时,计算机都输出3作为答案,但是做数学更进一步,在将方程输入Matlab之后,我也得到答案4.这里是怎么回事?
我可以想到的唯一的东西那里是错误的,这将是四舍五入的错误。但是,最多有5个舍入误差,加上使用双精度数学,我的最大误差将非常小,所以我怀疑是问题。
任何人能够
$
在C ++中,5/4 = 1, not 1.25 - 因为5和4都是整数,所以结果将是一个整数,因此结果的小数部分抛弃。
另一方面,5.0 / 4.0将等于约。 1.25,因为5.0和4.0中的至少一个是浮点数,因此结果也是浮点数。
Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken
You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions.
In C++, 5/4 = 1, not 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away.
On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point.
这篇关于不正确的浮点数学?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!