Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Created August 8, 2023 08:57
Show Gist options
  • Select an option

  • Save ZJUGuoShuai/3dbfd1be9d5186d0ea470d8b1041cdc5 to your computer and use it in GitHub Desktop.

Select an option

Save ZJUGuoShuai/3dbfd1be9d5186d0ea470d8b1041cdc5 to your computer and use it in GitHub Desktop.
Machine Epsilon 的作用
#include <limits>
#include <iostream>
int main() {
float eps = std::numeric_limits<float>::epsilon();
float a = 1.0f;
float b = a + eps;
float c = a + eps / 2.0f;
std::cout << "a == b: " << std::boolalpha << (a == b) << "\n"; // false
std::cout << "a == c: " << std::boolalpha << (a == c) << "\n"; // true
return 0;
}
@ZJUGuoShuai

Copy link
Copy Markdown
Author

常见用法:防止除零错误

在防止除零错误的时候,通常都要让被除数加上一个很小的数。为了不过多影响计算结果,这个数要尽可能小;但也不能太小,否则加上之后由于截断误差,新值就和原来的值是一样的。

因此,这个很小的数可以选择 Machine Epsilon。

例如,OpenCV 在实现 Phase Correlation 的时候,用到了 Machine Epsilon 来防止除零错误

sumIntensity += DBL_EPSILON; // prevent div0 problems...

@ZJUGuoShuai

Copy link
Copy Markdown
Author

如何自己获得 Machine Epsilon?

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

参考:https://stackoverflow.com/a/25155518/8102500

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment