Float vs Double

后端 未结 7 1835
-上瘾入骨i
-上瘾入骨i 2021-01-17 23:56

Is there ever a case where a comparison (equals()) between two floating point values would return false if you compare them as DOUBLE

7条回答
  •  情话喂你
    2021-01-18 00:09

    I'm perhaps not answering the OP's question but rather responding to some more or less fuzzy advice which require clarifications.

    Comparing two floating point values for equality is absolutely possible and can be done. If the type is single or double precision is often of less importance.

    Having said that the steps leading up to the comparison itself require great care and a thorough understanding of floating-point dos and don'ts, whys and why nots.

    Consider the following C statements:

    result = a * b / c;
    result = (a * b) / c;
    result = a * (b / c);
    

    In most naive floating-point programming they are seen as "equivalent" i e producing the "same" result. In the real world of floating-point they may be. Or actually, the first two are equivalent (as the second follows C evaluation rules, i e operators of same priority left to right). The third may or may not be equivalent to the first twp.

    Why is this?

    "a * b / c" or "b / c * a" may cause the "inexact" exception i e an intermediate or the final result (or both) is (are) not exact(ly representable in floating point format). If this is the case the results will be more or less subtly different. This may or may not lead to the end results being amenable to an equality comparison. Being aware of this and single-stepping through operations one at a time - noting intermediate results - will allow the patient programmer to "beat the system" i e construct a quality floating-point comparison for practically any situation.

    For everyone else, passing over the equality comparison for floating-poiny numbers is good, solid advice.

    It's really a bit ironic because most programmers know that integer math results in predictable truncations in various situations. When it comes to floating-point almost everyone is more or less thunderstruck that results are not exact. Go figure.

提交回复
热议问题