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:
MATLAB®
Fixed-Point Designer™
C compiler
See Supported Compilers.
You can use mex -setup
to change the default
compiler. See Change Default Compiler.
Create a local working folder, for example, c:\overflow
.
Change to the docroot\toolbox\fixpoint\examples
folder.
At the MATLAB command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
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.
Type | Name | Description |
---|---|---|
Function code | overflow.m | Entry-point MATLAB function |
Test file | overflow_test.m | MATLAB script that tests overflow.m |
Create a coder.FixptConfig
object, fixptcfg
,
with default settings.
fixptcfg = coder.config('fixpt');
Set the test bench name. In this example, the test
bench function name is overflow_test
.
fixptcfg.TestBenchName = 'overflow_test';
Set the default word length to 16.
fixptcfg.DefaultWordLength = 16;
fixptcfg.TestNumerics = true; fixptcfg.DetectFixptOverflows = true;
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 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%.
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.