c++对浮点数进行舍入以设置精度
我希望对浮点数进行舍入以设置精度并从函数返回结果。例如,我目前有以下功能:
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.333499999999999996
且 point.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,
==
不应该用来比较双精度数,你应该这样做:如果你不确定,你可以使用
abs
或fabs
的符号并相应地更改精度 1e-9。Generally,
==
should not be used to compare doubles, you should do something like :You can use
abs
orfabs
if you are not sure of the sign and change the precision 1e-9 accordingly.比较 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.