如何在 Scala 中比较浮点值?
据我所知,精确比较对于浮点值没有多大意义,因为 0.0001 实际上可能是 0.0001000...0001...我应该实现自己的比较函数来指定精度还是这有一个常见的做法吗?
我曾经在 C# 中使用以下内容(我怀疑这仍然是错误的,因为 Double 值可能根本无法表示 0.0001,甚至设置为常量(正如 Michael Borgwardt 所解释的 此处)):
public static bool AlmostEquals(this double x, double y, double precision = 0.0001)
{
if (precision < 0.0)
throw new ArgumentException();
return Math.Abs(x - y) <= precision;
}
我应该这样做吗Scala 有类似的东西吗?
As far as I know, exact comparison doesn't make much sense with floating point values as what is intended to be 0.0001 can actually be something like 0.0001000...0001... Should I implement my own comparison function to specify precision or is there a common practice for this?
I used to use the following with C# (which, I suspect, is still wrong as a Double value can be probably uncapable of representing 0.0001 at all, even set as a constant (as Michael Borgwardt explained here)):
public static bool AlmostEquals(this double x, double y, double precision = 0.0001)
{
if (precision < 0.0)
throw new ArgumentException();
return Math.Abs(x - y) <= precision;
}
Should I do something alike in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以做与 Java 中相同的事情。您还可以使用 Scala 的一些很酷的功能,并使用 ~= 方法来修饰 Double 类,该方法采用只需指定一次的隐式精度参数。
Yes, you can do the same thing as in Java. You could also use some of Scala's cool features and pimp the Double class with a ~= method that takes an implicit precision parameter that only needs to be specified once.
使用来自 scalautils
结果的公差:Double = 2.000001
res0: Boolean = true
res1: Boolean = false
更新:对于 Scala 2.11
Use Tolerance from scalautils
result: Double = 2.000001
res0: Boolean = true
res1: Boolean = false
Update: For Scala 2.11
或者使用 2.10...
Or with 2.10...