比较 C 中的浮点值
我想比较浮点值以确定列表中的最大数字。浮点的精度是固定的,小数点后为 6。
我应该将它们作为整数进行比较,如果它们相等,那么就去挖掘小数点后的值吗?
I want to compare float values to determine the biggest number in the list.The precision of the float is fixed, 6 after the decimal.
Should I just compare them as integer and if they are equal then go and dig the values after the decimal ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
比较浮点数的最简单方法是使用
<
运算符,如下所示The easiest way to compare floats is with the
<
operator, like so使用 DBL_EPSILON 作为需要接近双打的程度的基础。
使用 FLT_EPSILON 存在于浮点数中。
请参阅此答案以获取演示该技术的示例函数。
use DBL_EPSILON as a basis for how close to doubles need to be.
use FLT_EPSILON exists for floats.
see this answer for a sample function that demonstrates the technique.
如果你想找到最大的数字,为什么还需要担心比较是否相等呢?
If you want to find the biggest number, why would you need to worry about comparing for equality?
这取决于您没有告诉我们的事情。
等。
当您在浮点数组中拥有值时,我会执行以下操作:
That depends on things you don't tell us.
etc.
As you have the values in a float array, I would do the following:
执行此操作的代码如下所示:
Code to do this looks like the following:
以下文章提供了比较浮点值的各种替代方法。
http://randomascii.wordpress.com/ 2012/02/25/comparing-floating-point-numbers-2012-edition/
通常,查找浮点数之间的差异并检查如果差异在精度限制内,有助于比较浮点数。
但正如也提到的,对此没有完美的答案和实现,因为相邻浮点数之间的差异随大小而变化。因此,如果您知道程序将使用的值的范围,那么您可以选择适当的实现进行比较。
Following article provides various alternatives on comparing float values..
http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Usually, finding the difference between the floats and checking if the difference is within the precision limit, helps in comparing the floats.
But as also mentioned, there is no perfect answer and implementation for this because different between adjacent floats varies with the magnitude. Hence if you know the range of values which your program will use, then you can chose appropriate implementation for comparison.