C ++浮点precision [英] C++ floating point precision
问题描述
可能重复:结果
浮点不精确的例子
块引用>双A = 0.3;
。性病::法院precision(20);
性病::法院LT&;< A<<的std :: ENDL;结果:0.2999999999999999889
双A,B;
A = 0.3;
B = 0;
对于(CHAR I = 1; I< = 50;我++){
B = B + A;
};
。性病::法院precision(20);
性病::法院LT&;< B<<的std :: ENDL;结果:15.000000000000014211
所以..'A'小于它应该是。
但是,如果我们采取'A'的50倍 - 结果会大于它应该是。这是为什么?
而如何在这种情况下得到正确的结果呢?解决方案要得到正确的结果,不设置precision比大于可用此数值类型:
的#include<&iostream的GT;
#包括LT&;限制和GT;
诠释的main()
{
双A = 0.3;
。性病::法院precision(的std :: numeric_limits<双> :: digits10);
性病::法院LT&;< A<<的std :: ENDL;
双B = 0;
对于(CHAR I = 1; I< = 50;我++){
B = B + A;
};
。性病::法院precision(的std :: numeric_limits<双> :: digits10);
性病::法院LT&;< B<<的std :: ENDL;
}虽然如果循环5000次迭代,而不是50运行,累积误差会显示即使有这样的做法 - 这是浮点数是如何工作的。
Possible Duplicate:
Floating point inaccuracy examples
double a = 0.3; std::cout.precision(20); std::cout << a << std::endl;
result: 0.2999999999999999889
double a, b; a = 0.3; b = 0; for (char i = 1; i <= 50; i++) { b = b + a; }; std::cout.precision(20); std::cout << b << std::endl;
result: 15.000000000000014211
So.. 'a' is smaller than it should be. But if we take 'a' 50 times - result will be bigger than it should be.
Why is this? And how to get correct result in this case?
解决方案To get the correct results, don't set precision greater than available for this numeric type:
#include <iostream> #include <limits> int main() { double a = 0.3; std::cout.precision(std::numeric_limits<double>::digits10); std::cout << a << std::endl; double b = 0; for (char i = 1; i <= 50; i++) { b = b + a; }; std::cout.precision(std::numeric_limits<double>::digits10); std::cout << b << std::endl; }
Although if that loop runs for 5000 iterations instead of 50, the accumulated error will show up even with this approach -- it's just how floating-point numbers work.
这篇关于C ++浮点precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!