Comparing IEEE floats and doubles for equality

前端 未结 15 2308
南方客
南方客 2020-11-30 06:00

What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.

15条回答
  •  温柔的废话
    2020-11-30 06:53

    In numerical software you often want to test whether two floating point numbers are exactly equal. LAPACK is full of examples for such cases. Sure, the most common case is where you want to test whether a floating point number equals "Zero", "One", "Two", "Half". If anyone is interested I can pick some algorithms and go more into detail.

    Also in BLAS you often want to check whether a floating point number is exactly Zero or One. For example, the routine dgemv can compute operations of the form

    • y = beta*y + alpha*A*x
    • y = beta*y + alpha*A^T*x
    • y = beta*y + alpha*A^H*x

    So if beta equals One you have an "plus assignment" and for beta equals Zero a "simple assignment". So you certainly can cut the computational cost if you give these (common) cases a special treatment.

    Sure, you could design the BLAS routines in such a way that you can avoid exact comparisons (e.g. using some flags). However, the LAPACK is full of examples where it is not possible.

    P.S.:

    • There are certainly many cases where you don't want check for "is exactly equal". For many people this even might be the only case they ever have to deal with. All I want to point out is that there are other cases too.

    • Although LAPACK is written in Fortran the logic is the same if you are using other programming languages for numerical software.

提交回复
热议问题