Use Scaled Doubles to Avoid Precision Loss

This example uses the ex_scaled_double model to show how you can avoid precision loss by overriding the data types in your model with scaled doubles.

About the Model

In this model:

  • The Constant block output data type is fixdt(1,8,4).

  • The Bitwise Operator block uses the AND operator and the bit mask 0xFF to pass the input value to the output. Because the Treat mask as parameter is set to Stored Integer, the block outputs the stored integer value, S, of its input. The encoding scheme is V=SQ+B, where V is the real-world value and Q is the stored integer value. For more information, see Scaling.

Running the Example

  1. Open the ex_scaled_double model. At the MATLAB® command line, enter:

    addpath(fullfile(docroot,'toolbox','fixpoint','examples'))
    ex_scaled_double

  2. From the model Apps gallery, select Fixed-Point Tool.

    The Fixed-Point Tool opens.

  3. In the Fixed-Point Tool, click the Collect Ranges arrow button. In the menu, select Use current settings. Click Collect Ranges.

    The simulation runs. The Display block displays 4.125 as the output value of the Constant block. The Stored Integer Display block displays 0100 0010, which is the binary equivalent of the stored integer value. Precision loss occurs because the output data type, fixdt(1,8,4), cannot represent the output value 4.1 exactly.

  4. In the Fixed-Point Tool, click the Collect Ranges arrow button. In the menu, select Scaled double-precision. Click Collect Ranges.

    Note

    You cannot use a Data type override setting of Double because the Bitwise Operator block does not support floating-point data types.

    The simulation runs and this time the Display block correctly displays 4.1 as the output value of the Constant block. The Stored Integer Display block displays 65, which is the binary equivalent of the stored integer value. Because the model uses scaled doubles to override the data type fixdt(1,8,4), the compiled output data type changes to flts8_En4, which is the scaled doubles equivalent of fixdt(1,8,4). No precision loss occurs because the scaled doubles retain the information about the specified data type and scaling, and they use a double to hold the stored value.