c++对浮点数进行舍入以设置精度

发布于 2024-08-23 09:44:41 字数 597 浏览 1 评论 0原文

我希望对浮点数进行舍入以设置精度并从函数返回结果。例如,我目前有以下功能:

inline bool R3Point::
operator==(const R3Point& point) const
{
  // Return whether point is equal
  return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point.v[2]));
}

我想要做的是不直接进行 v[i] == point.v[i] 比较,我希望仅将数字与一定的设置精度,因此如果 v[i] = 0.333499999999999996point.v[i] = 0.33350000000000002,我的相等比较将得到 TRUE。

我知道有一个 c++ smanip set precision ( int n ); 函数,并且我发现它在使用 cout 在屏幕上显示输出时经常使用。但是,我不确定这是否可以在我描述的函数中使用。

谢谢。

I wish to round a floating point number to set precision and return the result from a function. For example, I currently have the following function:

inline bool R3Point::
operator==(const R3Point& point) const
{
  // Return whether point is equal
  return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point.v[2]));
}

What I wish to do is instead of doing a direct v[i] == point.v[i] comparison, I wish to compare only digits to a certain set precision, so that if v[i] = 0.33349999999999996 and point.v[i] = 0.33350000000000002, my equal comparison will result in TRUE.

I am aware that there's a c++ smanip setprecision ( int n ); function and I've seen it used a lot when displaying output on screen using cout. However, I'm not sure if this can be used within the function like I described.

Thanks.

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

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

发布评论

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

评论(2

魄砕の薆 2024-08-30 09:44:41

一般来说,==不应该用来比较双精度数,你应该这样做:

if(v[0] - point.v[0] < 1e-9) { }

如果你不确定,你可以使用absfabs的符号并相应地更改精度 1e-9。

Generally, == should not be used to compare doubles, you should do something like :

if(v[0] - point.v[0] < 1e-9) { }

You can use abs or fabs if you are not sure of the sign and change the precision 1e-9 accordingly.

神魇的王 2024-08-30 09:44:41

比较 2 个浮点数(例如 a 和 b),最好使用以下公式来完成:abs(ab) <精确。其中abs(x)是绝对值函数,精度是一些小的正数。通常,您希望将精度设置为要比较的数字本身的绝对值的函数。

Comparing 2 floating point numbers (say a and b), is best done using the following: abs(a-b) < precision. Where abs(x) is the absolute value function, and precision is some small positive number. Often you want to set the precision as a function of the absolute value of the numbers being compared themselves.

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