Ada 95 Quality and Style Guide Chapter 7

Chapter 7: Portability - TOC - 7.2 NUMERIC TYPES AND EXPRESSIONS

7.2.7 Relational Tests

guideline

  • Consider using <= and >= to do relational tests on real valued arguments, avoiding the <, >, =, and /= operations.

  • Use values of type attributes in comparisons and checking for small values.
  • example

    The following examples test for (1) absolute "equality" in storage, (2) absolute "equality" in computation, (3) relative "equality" in storage, and (4) relative "equality" in computation:

    abs (X - Y) <= Float_Type'Model_Small                -- (1)
    abs (X - Y) <= Float_Type'Base'Model_Small           -- (2)
    abs (X - Y) <= abs X * Float_Type'Model_Epsilon      -- (3)
    abs (X - Y) <= abs X * Float_Type'Base'Model_Epsilon -- (4)
    

    And, specifically, for "equality" to 0:

    abs X <= Float_Type'Model_Small                      -- (1)
    abs X <= Float_Type'Base'Model_Small                 -- (2)
    abs X <= abs X * Float_Type'Model_Epsilon            -- (3)
    abs X <= abs X * Float_Type'Base'Model_Epsilon       -- (4)
    

    rationale

    Strict relational comparisons ( <, >, =, /= ) are a general problem with computations involving real numbers. Because of the way comparisons are defined in terms of model intervals, it is possible for the values of the comparisons to depend on the implementation. Within a model interval, the result of comparing two values is nondeterministic if the values are not model numbers. In general, you should test for proximity rather than equality as shown in the examples. See also Rationale (1995, G.4.1 and G.4.2.).

    Type attributes are the primary means of symbolically accessing the implementation of the Ada numeric model. When the characteristics of the model numbers are accessed by type attributes, the source code is portable. The appropriate model numbers of any implementation will then be used by the generated code.

    Although 0 is technically not a special case, it is often overlooked because it looks like the simplest and, therefore, safest case. But in reality, each time comparisons involve small values, you should evaluate the situation to determine which technique is appropriate.

    notes

    Regardless of language, real-valued computations have inaccuracy. That the corresponding mathematical operations have algebraic properties usually introduces some confusion. This guideline explains how Ada deals with the problem that most languages face.


    < Previous Page Search Contents Index Next Page >
    1 2 3 4 5 6 7 8 9 10 11
    TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC
    Appendix References Bibliography