Why my double can contain a value below the machine epsilon?

落爺英雄遲暮 提交于 2019-12-01 05:34:20

问题


I was solving an equation using double precision and I got -7.07649e-17 as a solution instead of 0.

I agree it's close enough that I can say it's equal but I've read that the machine epsilon for the C++ double type is 2^-52 which is larger than the value I get.

So why do I have an inferior value than the machine epsilon? Why isn't the value rounded to zero?

It's not a big deal but when I do a logical test it appears that my value is not zero...


回答1:


There are two different constants in this story. One is epsilon, which is a minimal value that when added to 1.0 produces a value different from 1.0. If you add a smaller value to 1.0 you will again get a 1.0, because there are physical limits to the representation of a number in a computer. But there are values that are less than epsilon and greater than zero. Smallest such number for a double you get with std::numeric_limits<double>::min.

For reference, you get epsilon with std::numeric_limits<double>::epsilon.




回答2:


You are not guaranteed that rounding will take place at any particular time. The C++ standard permits the implementation to use additional precision pretty much anywhere it wants to and many real-world implementations do exactly that.




回答3:


A common solution for the floating point precision problem is to define an epsilon value yourself and compare to that instead of zero.

e.g.

double epsilon = 0.00001;
if (abs(value) < epsilon) // treat value as 0 in your code


来源:https://stackoverflow.com/questions/43678480/why-my-double-can-contain-a-value-below-the-machine-epsilon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!