问题描述
在F#中.如何有效地比较浮点数是否相等?它也应该适用于非常大和非常小的值.我正在考虑先比较指数,然后比较有效位数(Mantissa),而忽略其52位中的最后4位.那是一个好方法吗?如何获得浮点数的指数和有效位数?
In F#. How to efficiently compare floats for equality that are almost equal? It should work for very large and very small values too. I am thinking of first comparing the Exponent and then the Significand (Mantissa) while ignoring the last 4 bits of the its 52 bits. Is that a good approach? How can I get the Exponent and Significand of a float?
推荐答案
F#float
只是System.Double
的简写.在这种情况下,您可以使用 BitConverter.DoubleToInt64Bits 有效(和安全!)将F#float
值投射"到int64
的方法;如John在其评论中所述,这很有用,因为它避免分配byte[]
.您可以使用一些简单的按位运算从int64
中获取指数和有效数.
An F# float
is just a shorthand for System.Double
. That being the case, you can use the BitConverter.DoubleToInt64Bits method to efficiently (and safely!) "cast" an F# float
value to int64
; this is useful because it avoids allocating a byte[]
, as John mentioned in his comment. You can get the exponent and significand from that int64
using some simple bitwise operations.
如John所说,简单检查相对精度可能会更好.对于许多用例,它可能是最快的解决方案,并且足够接近"(例如,检查迭代求解器是否已收敛于解决方案).如果您需要特定于 的精度,请查看NUnit的代码-它具有一些不错的API,可以断言值在期望值的一定百分比或数量之内.
As John said though, you're probably better off with a simple check for relative accuracy. It's likely to be the fastest solution and "close enough" for many use cases (e.g., checking to see if an iterative solver has converged on a solution). If you need a specific amount of accuracy, take a look at NUnit's code -- it has some nice APIs for asserting that values are within a certain percentage or number of ulps of an expected value.
这篇关于F#-如何比较浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!