简体   繁体   English

浮点数学不正确?

[英]Incorrect floating point math?

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? 每次我运行该程序时,计算机会吐出3作为答案,但是手动进行数学计算,我得到4.更进一步,在将方程式输入Matlab之后,我也得到了答案4.这里有什么进展?

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. 然而,最多有5个舍入误差,再加上使用双精度数学,我的最大误差将非常小,所以我怀疑这是问题所在。

Anyone able to offer any solutions? 有谁能提供任何解决方案?

Thanks in advance, 提前致谢,

-Faken -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. 在C ++中,5/4 = 1, 而不是 1.25 - 因为5和4都是整数,所以结果将是一个整数,因此结果的小数部分被丢弃。

On the other hand, 5.0/4.0 will equal approx. 另一方面,5.0 / 4.0将等于约。 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. 1.25因为5.0和4.0中至少有一个是浮点数,所以结果也是浮点数。

You're confusing integer division with floating point division. 你将整数除法与浮点除法混淆了。 3 is the correct answer with integer division. 3是整数除法的正确答案。 You'll get 4 if you convert those values to floating point numbers. 如果将这些值转换为浮点数,您将获得4。

Some of this is being evaluated using integer arithmetic. 其中一些是使用整数运算进行评估的。 Try adding a decimal place to your numbers, eg 6.0 instead 6 to tell the compiler that you don't want integer arithmetic. 尝试在数字中添加一个小数位,例如6.0而不是6来告诉编译器你不需要整数运算。

s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;

yields 3 收益率3

s2 = -(0.*13.)/84.+6./42.-0./84.+24./12.+(6.*13.)/42.;

does what you are expecting. 做你所期待的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM