Main Content

Detect Overflows

This example shows how to detect overflows using the fiaccel function. At the numerical testing stage in the conversion process, the tool simulates the fixed-point code using scaled doubles. It then reports which expressions in the generated code produce values that would overflow the fixed-point data type.


To complete this example, you must install the following products:

Create a New Folder and Copy Relevant Files

  1. Create a local working folder, for example, c:\overflow.

  2. Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB command line, enter:

    cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples')) 

  3. Copy the overflow.m and overflow_test.m files to your local working folder.

    It is best practice to create a separate test script to do all the pre- and post-processing such as loading inputs, setting up input values, calling the function under test, and outputting test results.

    Function codeoverflow.mEntry-point MATLAB function
    Test fileoverflow_test.mMATLAB script that tests overflow.m

 The overflow Function

 The overflow_test Function

Set Up Configuration Object

  1. Create a coder.FixptConfig object, fixptcfg, with default settings.

    fixptcfg = coder.config('fixpt');
  2. Set the test bench name. In this example, the test bench function name is overflow_test.

    fixptcfg.TestBenchName = 'overflow_test';
  3. Set the default word length to 16.

    fixptcfg.DefaultWordLength = 16;

Enable Overflow Detection

fixptcfg.TestNumerics = true;
fixptcfg.DetectFixptOverflows = true;

Set fimath Options

Set the fimath Product mode and Sum mode to KeepLSB. These settings models the behavior of integer operations in the C language.

fixptcfg.fimath = 'fimath( ''RoundingMethod'', ''Floor'', ''OverflowAction'', ''Wrap'', ''ProductMode'', ''KeepLSB'', ''SumMode'', ''KeepLSB'')';

Convert to Fixed Point

Convert the floating-point MATLAB function, overflow, to fixed-point MATLAB code. You do not need to specify input types for the fiaccel command because it infers the types from the test file.

fiaccel -float2fixed fixptcfg overflow

The numerics testing phase reports an overflow.

Overflow error in expression 'acc + b( j )*z( k )'. Percentage of Current Range = 104%.

Review Results

Determine if the addition or the multiplication in this expression overflowed. Set the fimath ProductMode to FullPrecision so that the multiplication will not overflow, and then run the fiaccel command again.

fixptcfg.fimath = 'fimath( ''RoundingMethod'', ''Floor'', ''OverflowAction'', ''Wrap'', ''ProductMode'', ''FullPrecision'', ''SumMode'', ''KeepLSB'')';
fiaccel -float2fixed fixptcfg overflow

The numerics testing phase still reports an overflow, indicating that it is the addition in the expression that is overflowing.