微调 == 运算符以匹配双精度

发布于 2024-12-08 14:42:37 字数 197 浏览 3 评论 0原文

在我的代码中有一个我正在计算的参数。在很多测试运行中,该参数应该为0。由于该参数是通过多次加减计算的,因此它不完全是0,但小于10^-10。目前我正在使用:

double tol = pow(10,-10);
if (fabs(delta_U) < tol)){//whatever
}

有更优雅的方法吗?

In my code there is a parameter I am calculating. During many of the test runs, this parameter should be 0. Since the parameter is calculating through multiple additions and subtractions, it is not exactly 0 but it is less than 10^-10. Currently I am using:

double tol = pow(10,-10);
if (fabs(delta_U) < tol)){//whatever
}

Is there a more elegant way to do so?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱,才寂寞 2024-12-15 14:42:37

看起来不错。您可以直接写出容差,而不是使用 pow 进行计算。

double tol = 1e-10;

It looks fine. You could just write the tolerance directly, instead of computing it with pow.

double tol = 1e-10;
疯了 2024-12-15 14:42:37

jpalecek 是正确的 - 节省了常量的计算。

我不知道计算的性质,但您可以

  • 通过修改计算和运算符的顺序来减少错误
  • 可能使计算使用整数

jpalecek is correct - saves computation of a constant.

I do not know the nature of the calculations but you could either possibly

  • Reduce the errors by modifying the order of calculations and operators
  • Possibly make the calculation use integers
无可置疑 2024-12-15 14:42:37

将其包装在一个函数中,以便更清楚您要做什么:

if (near_zero(delta_U))
{
   // ...
}

在哪里:

inline bool near_zero(double d)
{
   return fabs(d) < 1e-10;
}

Wrap it in a function so it is more clear what you are trying to do:

if (near_zero(delta_U))
{
   // ...
}

where:

inline bool near_zero(double d)
{
   return fabs(d) < 1e-10;
}
最终幸福 2024-12-15 14:42:37

您可以用科学记数法指定浮点数:

if (fabs(delta_U) < 1e-10)
{
   //whatever
}

You can specify floating point in scientific notation:

if (fabs(delta_U) < 1e-10)
{
   //whatever
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文